Sobes.tech
Middle

What are the features of working with function expressions and function declarations in JavaScript?

sobes.tech AI

Answer from AI

Function declaration (function declaration) is hoisted by the interpreter, meaning it can be called before its definition in the code. It is created at the moment of script parsing. It has a name.

// functionDeclaration(); // Call before definition is possible

function functionDeclaration() {
  // Function code
}

Function expression (functional expression) is not hoisted. It is executed as part of an expression. It can be anonymous or have a name (named functional expression). A named functional expression allows recursive calls within itself and shows the name in the debugger.

// functionExpression(); // Call before definition will cause an error

const functionExpression = function() {
  // Function code
};

// Named functional expression
const namedFunctionExpression = function myFunctionName() {
  // Function code
  // Can call myFunctionName() inside this function
};

Main differences:

Feature Function Declaration Function Expression
Hoisting Yes No
Creation time During script parsing At runtime
Presence of name Mandatory Optional
Usage in conditions Not recommended Recommended

Example of usage in conditions:

// Not recommended for Function Declaration
if (condition) {
  function doSomething() {
    // ...
  }
}

// Preferable for Function Expression
let doSomething;
if (condition) {
  doSomething = function() {
    // ...
  };
}