1

I'm learning about functions in Javascript but getting confused about the use of function declaration and function expression.

Let's say I have the following code:

function callFunction(fn) {
  fn();
}

// function expression
var sayHello1 = function() {
  console.log("Hello World!");
}

// function declaration
function sayHello2() {
  console.log("Hello World!");
}

callFunction(sayHello1); // Hello World!
callFunction(sayHello2); // Hello World!

We can easily see that when passing sayHello1 (function expression) and sayHello2 (function declaration) into callFunction(fn), both generate the same output Hello World!.

Is there any real case that I must use only function declaration/ function expression or I can use them interchangeably all the time?

Thanks so much!

DunDev
  • 210
  • 2
  • 13

1 Answers1

2

They both have their use-cases. Function declarations are hoisted to the top of your script and can be called before they're definition appears while function expressions can only be called after the declaration.

sayHello1(); // Won't work since variable expression is created after call
sayHello2(); // Will work since function declarations are hoisted

var sayHello1 = function() {
  console.log("Hello World!");
}

function sayHello2() {
  console.log("Hello World!");
}

A named function expression can be useful for recursive calls:

var sayHello1 = function sayHelloFunc() {
  if (/* something */) {
    sayHelloFunc()
  }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119