function declarations vs function expressions in Javascript 🤔✌️

rajusaha

Raju Saha

Posted on June 30, 2024

function declarations vs function expressions in Javascript 🤔✌️

When it comes to defining functions in JavaScript, there are two primary ways to do so: function declarations and function expressions. While they may seem similar, there are key differences between them that can impact the behavior of your code. Let’s explore these differences in detail.

Function Declaration

A function declaration is a standard way of defining a function using the function keyword, followed by the name of the function.

Characteristics of Function Declarations:

  • Named Functions: They are declared with a specific name.
  • Not Assignable to Variables: Function declarations stand alone and are not typically assigned to variables.
  • Hoisted: Function declarations are hoisted, meaning they are available before any other code execution. You can call a function declared this way before its definition in the code.
// Calling the function before its definition due to hoisting
Declaration();

function Declaration(){
    console.log('function declaration is called');
}

// Calling the function after its definition
Declaration();

Enter fullscreen mode Exit fullscreen mode

Function Expression

A function expression involves defining a function as part of an expression. This usually means assigning a function to a variable.

Characteristics of Function Expressions:

  • Assigned to Variables: Function expressions are typically assigned to a variable.
  • Not Hoisted: Function expressions are not hoisted, meaning they can only be accessed after their definition.
  • Use Cases: Function expressions are often used when you need to pass a function as an argument to another function or when you want to define functions conditionally.
// Trying to call the function before its definition will result in an error
expression(); // Will give an error

// Defining the function as a function expression
const expression = function(){
    console.log('function expression');
};

// Calling the function after its definition
expression();

Enter fullscreen mode Exit fullscreen mode

Key Differences

Syntax and Structure:

  • Function Declaration:function Declaration() { // code }
  • Function Expression: const expression = function() { // code };

Hoisting

  • Function Declaration: Hoisted to the top of the scope.
  • Function Expression: Not hoisted; must be defined before use.

Naming:

  • Function Declaration: Named functions.
  • Function Expression: Can be anonymous or named, but usually assigned to variables.

Use Cases

  • Function Declaration: Best for defining standard, reusable functions.
  • Function Expression: Useful for conditional definitions and passing functions as arguments.
💖 💪 🙅 🚩
rajusaha
Raju Saha

Posted on June 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related