Ufuk's Blog

Function expressions vs. function declarations

☕️ 1 min read

In this post, I’ll be using ES5 syntax which most of the JavaScript developers are used to. Actually, in ES6 syntax there is another way of writing a function called arrow function but it’s not the concern of this article.

// Function declaration
function sayHello(name) {
  return 'Hello ' + name;
}

// Function expression
var sayHello = function(name) {
  return 'Hello ' + name;
};

They can do the same job but there is a big difference between them. Let’s see what that is!

Hoisting

Function declarations are known by the browser before any code is run. It means that you can call a function before you declare it. Let’s see by two examples.

// This code not surprisingly works
function sayHello(name) {
  return 'Hello ' + name;
}
sayHello('Ufuk');

// This code also works!
sayHello('Ufuk');
function sayHello(name) {
  return 'Hello ' + name;
}

Instead of function declarations if you use function expressions there will be an important difference in the runtime.

// This code works
var sayHello = function(name) {
  return 'Hello ' + name;
};
sayHello('Ufuk');

// This code does not work!
sayHello('Ufuk');
var sayHello = function(name) {
  return 'Hello ' + name;
};

Which one to use?

That depends on the situation and preference of the developer. Personally, I prefer function expressions. They give us more reliable way of writing and using functions. If you use function expressions, you can’t call a function before you declare it like I said earlier.