What is var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:


Solution


// TypeError: functionOne is not a function


functionOne();

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

And, a function declaration:


// Outputs: "Hello!"


functionTwo();

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

Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.

'use strict';    
{ // note this block!
  function functionThree() {
    console.log("Hello!");
  }
}
functionThree(); // ReferenceError

No comments:

Post a Comment

Angular's new httpResource and a bonus hidden feature

  The first   release candidate   for   Angular 19.2   is out, and it includes the new experimental   httpResource . This is essentially a s...

Best for you