Skip to main content

Command Palette

Search for a command to run...

Mastering JavaScript Functions: Understanding Function Declarations vs Function Expressions

Published
4 min readView as Markdown
Mastering JavaScript Functions: Understanding Function Declarations vs Function Expressions

Introduction

Imagine you run a coffee shop. Instead of manually brewing coffee every time a customer orders, you use a coffee machine. You press a button, and the machine follows a predefined set of instructions to prepare the coffee. This makes your process efficient, consistent, and reusable—no need to start from scratch for every order.

In JavaScript, functions work the same way! They are reusable blocks of code that perform specific tasks whenever called. Instead of writing the same logic multiple times, you define a function once and call it whenever needed—just like pressing a button on a coffee machine.

This article explores two primary ways of defining functions—Function Declarations and Function Expressions—and how they impact your code execution. Let’s dive in! 🚀

1. Function Declarations

A Function Declaration is a straightforward way to define a function using the function keyword followed by a function name. These functions are hoisted, meaning they can be called before they are defined in the script.

Syntax:

function functionName(parameters) {
    // Function body
    return value;  // Optional
}

Example:

function greet(name) {
    return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Output: Hello, Alice!

Key Characteristics of Function Declarations

  1. Hoisting:

    • Function declarations are hoisted, meaning they can be called before they are defined in the code.

    • Example:

    sayHello(); // Works fine! Output: Hello, World!

    function sayHello() {
        console.log("Hello, World!");
    }
  • The function is moved to the top of its scope during the execution phase.
  1. Named Functions:

    • Function declarations always have a name, making them easier to read and debug.
  2. Global Scope Access (if declared outside a block):

    • These functions are available throughout the entire script.

2. Function Expressions

A Function Expression involves defining a function and assigning it to a variable. Unlike function declarations, function expressions are not hoisted, meaning they cannot be used before their definition.

Syntax:

const functionName = function(parameters) {
    // Function body
    return value; // Optional
};

Example:

const greet = function(name) {
    return `Hello, ${name}!`;
};

console.log(greet("Bob")); // Output: Hello, Bob!

Key Characteristics of Function Expressions

  1. Not Hoisted:

    • Function expressions are not hoisted, so they cannot be called before they are defined.

    • Example:

    console.log(square(4)); // ReferenceError: Cannot access 'square' before initialization

    const square = function(num) {
        return num * num;
    };
  • The function is only available after its definition.
  1. Anonymous or Named:

    • Function expressions can be anonymous (without a function name) or named (with a function name).

    • Anonymous Function Expression:

        const add = function(a, b) {
            return a + b;
        };
      
    • Named Function Expression (Useful for debugging):

        const multiply = function multiplyNumbers(a, b) {
            return a * b;
        };
        console.log(multiply(3, 4)); // Output: 12
      
  2. Used as Callbacks:

    • Function expressions are often used for callbacks in functions like setTimeout(), map(), and filter().

    • Example:

        setTimeout(function() {
            console.log("This runs after 2 seconds!");
        }, 2000);
      

Comparison: Function Declaration vs Function Expression

FeatureFunction DeclarationFunction Expression
HoistingYes, can be called before definitionNo, must be defined first
SyntaxUses the function keyword with a nameAssigned to a variable
ExecutionAvailable throughout the scopeAvailable only after definition
Use CasesBest for defining reusable functionsCommonly used for callbacks and one-time execution
DebuggingEasier to debug due to function nameAnonymous functions are harder to debug

PlantUML diagram

Conclusion

Both function declarations and function expressions are essential in JavaScript, each serving its own purpose.

  • Use function declarations when you want to define a function that can be used throughout your script.

  • Use function expressions when you need flexibility, such as passing functions as arguments or creating functions dynamically.

By understanding these differences, you can write more structured, readable, and efficient JavaScript code. 🚀

More from this blog

Saleh's

41 posts