JavaScript - Function Declarations and Function Expressions

1. Function Declaration

A function declaration is the traditional way of defining a function in JavaScript.

Syntax

function functionName(parameters) {
    // Code to execute
}

Example

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

console.log(greet("Alice"));
console.log(greet("Bob"));

Output:

Hello, Alice!
Hello, Bob!

Key Features

  • Must have a name.

  • Can be called before or after its definition due to hoisting.

  • Stored in memory during the compilation phase.


2. Function Expression

A function expression means assigning a function to a variable.
It can be named or anonymous.

Syntax

const functionName = function(parameters) {
    // Code to execute
};

Example

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

console.log(greet("Alice"));
console.log(greet("Bob"));

Output:

Hi, Alice!
Hi, Bob!

Key Features

  • Can be anonymous (no name needed).

  • Not hoisted → must be defined before calling.

  • Useful when passing functions as arguments.


3. Difference Between Function Declaration & Function Expression

Feature Function Declaration Function Expression
Definition Uses function keyword with a name Assigns a function to a variable
Name Must have a name Can be anonymous or named
Hoisting ✅ Yes, can call before definition ❌ No, must define first
When evaluated At compile time At runtime
Best use case General-purpose reusable functions Callback functions, inline functions

4. Hoisting Difference

Example with Function DeclarationWorks

sayHello("Alice"); // Works even before declaration

function sayHello(name) {
    console.log(`Hello, ${name}`);
}

Output:

Hello, Alice
  • Reason: Function declarations are hoisted.


Example with Function ExpressionError

sayHello("Bob"); // ❌ ReferenceError

const sayHello = function(name) {
    console.log(`Hello, ${name}`);
};

Output:

ReferenceError: Cannot access 'sayHello' before initialization
  • Reason: Function expressions are not hoisted.


5. Named vs Anonymous Function Expressions

Anonymous Function Expression

const greet = function(name) {
    console.log(`Hi, ${name}`);
};
greet("Emma");

Named Function Expression

const greet = function sayHi(name) {
    console.log(`Hi, ${name}`);
};
greet("Liam");
  • The internal name sayHi can be useful for debugging stack traces.


6. Function Expressions as Callbacks

Function expressions are often used as callbacks:

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

Or using arrow functions:

setTimeout(() => {
    console.log("Arrow function callback");
}, 2000);

7. Quick Summary

Feature Function Declaration Function Expression
Syntax function name() {} const name = function() {};
Name Required ✅ Yes ❌ Optional
Hoisted ✅ Yes ❌ No
Execution Time Compile time Runtime
Best For Reusable functions Inline callbacks