JavaScript tip 1: Function Expressions

If you are creating your JavaScript functions using Function Declarations, a good tip is to switch to Function Expressions.

First here is an example of a Function Declaration:

function declared() {
  console.log("First declared function.");
}

Sadly because of variable hoisting, which means that declarations are hoisted to the top of their scope in JavaScript, we can run into some problems likewise:

function declared() {
  console.log("First declared function.");
}

declared();

function declared() {
  console.log("Overwriting declared function.");
}

In this case since both Function Declarations are hoisted to the top we end up with “Overwriting declared function.” being logged out to the console.

Here’s what the code looks like after hoisting:

function declared() {
  console.log("First declared function.");
}

function declared() {
  console.log("Overwriting declared function.");
}

declared();

Function Expressions provide another way to create a function and avoid this kind of problem. Here’s the previous example using Function Expressions:

var expression = function() {
  console.log("First Function Expression.");
};

expression();

var expression = function() {
  console.log("Not gonna happen!");
};

Which this time is returning “First Function Expression.”. While both expression variable declarations are hoisted up, their definitions aren’t.

Here’s this last example after hoisting:

var expression = undefined;
var expression = undefined;

expression = function() {
  console.log("First Function Expression.");
};

expression();

expression = function() {
  console.log("Not gonna happen!");
};

It’s thus safer to use Function Expressions over Function Declarations.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s