Open In App

Difference between Function Declarations & Function Expressions in JavaScript

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Function Declarations:

  • Function declarations are defined using the function keyword followed by a name and a function body.
  • They are hoisted to the top of their containing scope during the compilation phase, meaning they can be called before they are declared.
  • Function declarations can be used to create named functions that can be called from anywhere within the scope in which they are declared.
  • They have a distinct name, which is used for identification and debugging purposes.

Example: Below is an example of a Function Declaration.

Javascript




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


Output

Hello!

Function Expressions:

  • Function expressions involve assigning a function to a variable or a property of an object.
  • They are not hoisted, meaning they cannot be called before the expression is evaluated.
  • Function expressions can be either named or anonymous, and they can be assigned to variables, passed as arguments to other functions, or returned from other functions.
  • They offer more flexibility as they can be used as values in assignments or passed around as parameters.

Example: Below is an example of Function Expression.

Javascript




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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads