Function Declarations VS Function Expressions

Last Updated on 11 June 2020

In JavaScript, there are two different ways to create a function:
Function Declarations and Function Expressions

// Function Declaration
function jorcus() { ... }
// Function Expression
const jorcus = function() { ... }

Function Hoisting

The function expression cannot be load before it executed, it needs to execute before it runs, otherwise it will throw an error. However, the function declarations are allowed to run even before it execute because it loads before any code is executed.

Example: Function Declaration

console.log(jorcus()); // It works! Function declaration can works before it run.
function jorcus() { return 100; }

Example: Function Expression

console.log(jorcus()); // Uncaught ReferenceError: Cannot access 'jorcus' before initialization
const jorcus = function() { return 100; }

The advantages of Function Expression

Immediately Invoked Function Expression (IIFE)

The IIFE will not affect the variable globally, it’s only can use locally to the function expression itself to protect it not to affect global variable.

var a = 5;
	var a = 10;
	console.log(a); // 10
console.log(a); // 5 - It's not 10, because the a in the function above are locally inside the parentheses. Hence, it will not works outside of it.

When to use function declaration vs function expression?

When you need calling the function before it runs, use function declaration. Otherwise, I would suggest to use the named function expression to create a function. This is because function declaration can harm readability and maintainability of the software when the software getting larger and complex. It can also cause some unexpected issues since function declaration are hoist.

With function expression, you can’t call it before it runs, It’s makes the code more structured. Therefore, it’s better to use named function expression instead of the function declaration when creating a function.

Leave a Comment