Skip to main content

Command Palette

Search for a command to run...

Functions and Function Declaration vs. Function Expression in JavaScript

Updated
3 min readView as Markdown
Functions and Function Declaration vs. Function Expression in JavaScript

A. Functions

In JavaScript, functions are reusable blocks of code that perform specific tasks.

There are different ways to define and use functions:

  1. Function Declaration

  2. Function Expression

  3. Arrow Function

  4. Immediately Invoked Function Expression (IIFE)

  5. Higher-Order Function

  6. Callback function

  7. Closures

1. Function Declaration

Understanding JavaScript functions, including their concepts, usage, and differences between function declarations and function expressions.

function greet(name) { 
    return Hello, ${name}!; 
} 
console.log(greet("John")); // Output: Hello, John!

Default Parameters:

If an argument is not provided, the default value is used.

function greet(name = "Guest") {
    return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!

Rest Parameters:

Used to pass an indefinite number of arguments as an array.

function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

2. Function Expression

A function assigned to a variable. It is not hoisted.

const greet = function(name) {
    return `Hello, ${name}!`;
};
console.log(greet("John")); // Output: Hello, John!

3. Arrow Function (ES6)

A concise way to write functions.

const greet = (name) => `Hello, ${name}!`;
console.log(greet("John")); // Output: Hello, John!

4. Immediately Invoked Function Expression (IIFE)

A function that runs immediately after it is defined.

(function() {
    console.log("This runs immediately!");
})();

5. Higher-Order Function

A function that takes another function as an argument or returns one

function operate(a, b, callback) {
    return callback(a, b);
}

const add = (x, y) => x + y;
console.log(operate(5, 3, add)); // Output: 8

6. Callback Function

A function passed as an argument to another function.

function fetchData(callback) {
    setTimeout(() => {
        callback("Data received!");
    }, 2000);
}

fetchData((message) => console.log(message)); // Output (after 2 sec): Data received!

7. Closures

A function that remembers variables from its outer scope.

function counter() {
    let count = 0;
    return function () {
        count++;
        return count;
    };
}

const increment = counter();
console.log(increment()); // Output: 1
console.log(increment()); // Output: 2

B. Function Declaration vs. Function Expression in JavaScript

Both function declarations and function expressions define functions in JavaScript, but they have key differences in syntax and behavior.

Function Declaration

  • A function is declared using the function keyword.

  • It is hoisted, meaning it can be called before it is defined in the code.

hello(); // ✅ Works due to hoisting

function hello() {
    console.log("Hello, World!");
}

hello(); // ✅ Works normally

Function Expression

  • A function is assigned to a variable (can be named or anonymous).

  • It is not hoisted, meaning it cannot be called before its definition.

greet(); // ❌ ReferenceError: Cannot access 'greet' before initialization

const greet = function () {
    console.log("Hello from function expression!");
};

greet(); // ✅ Works normally

Key Differences

FeatureFunction DeclarationFunction Expression
Hoisting✅ Hoisted❌ Not hoisted
Can be called before definition?✅ Yes❌ No
Syntaxfunction name() {}const name = function() {}
Use CaseBest for defining reusable functionsUseful for callbacks & closures

Here’s a simple diagram illustrating the difference between Function Declarations and Function Expressions:

Diagram Representation

javascriptCopyEdit                     ┌──────────────────┐
                     │  Function Declaration  │
                     └────────▲──────────┘
                              │
                              │ Hoisted (Can be called before definition)
                              │
                    ┌─────────┴──────────┐
                    │ function greet() {} │
                    └────────────────────┘

                     ┌──────────────────┐
                     │  Function Expression  │
                     └────────▲──────────┘
                              │
                              │ NOT Hoisted (Cannot be called before definition)
                              │
         ┌────────────────────────────────────────┐
         │ const greet = function() {}            │
         │ const greet = () => {}  (Arrow Fn)     │
         └────────────────────────────────────────┘