Open In App

Difference between Function Declarations & Function Expressions in JavaScript

Function Declarations:

Example: Below is an example of a Function Declaration.




function greet() {
    console.log("Hello!");
}
greet(); // Output: Hello!

Output

Hello!

Function Expressions:

Example: Below is an example of Function Expression.




const greet = function() {
    console.log("Hello!");
};
greet(); // Output: Hello!

Output

Hello!

Key Differences:

  1. Hoisting: Function declarations are hoisted to the top of their containing scope, allowing them to be called before they are declared. Function expressions are not hoisted, so they cannot be called before the expression is evaluated.
  2. Usage: Function declarations are typically used for creating named functions that are available throughout their containing scope. Function expressions are more flexible and can be used as anonymous functions or assigned to variables, allowing them to be passed around as values.
  3. Syntax: Function declarations use the function keyword followed by a name, while function expressions involve assigning a function to a variable or property.
Article Tags :