Skip to content

2. Functions (Very Important) ​

Functions are reusable blocks of code that perform specific tasks.

They help make code cleaner, reusable, and modular.


Topics Covered ​

  • Function Declaration
  • Function Expression
  • Arrow Function
  • Callback Function
  • Higher-Order Function
  • IIFE
  • Pure Function
  • Closures

1. Function Declaration ​

A normal function created using the function keyword.


Syntax ​

js
function functionName() {
  // code
}

Example ​

js
function greet() {
  console.log("Hello");
}

greet();

Function with Parameters ​

Parameters are values passed into functions.

js
function add(a, b) {
  return a + b;
}

console.log(add(2, 3));

Explanation ​

  • a and b are parameters
  • 2 and 3 are arguments
  • return sends back result

Features ​

  • Hoisted
  • Can be called before declaration
js
sayHi();

function sayHi() {
  console.log("Hi");
}

2. Function Expression ​

A function stored inside a variable.


Syntax ​

js
const greet = function () {
  console.log("Hello");
};

Example ​

js
const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(2, 4));

Features ​

  • Not fully hoisted
  • Commonly used in modern JavaScript
  • Can be anonymous

Difference Between Function Declaration and Function Expression ​

FeatureFunction DeclarationFunction Expression
HoistedYesNo
SyntaxDirect functionStored in variable
Calling before declarationAllowedNot allowed

3. Arrow Function ​

Short syntax introduced in ES6.


Syntax ​

js
const add = (a, b) => {
  return a + b;
};

Shorter Syntax ​

js
const add = (a, b) => a + b;

If only one line exists, return is automatic.


Example ​

js
const square = (num) => num * num;

console.log(square(5));

Difference Between Normal Function and Arrow Function ​


Normal Function ​

js
function greet() {
  console.log("Hello");
}

Arrow Function ​

js
const greet = () => {
  console.log("Hello");
};

Main Differences ​

FeatureNormal FunctionArrow Function
SyntaxLongerShort
Own thisYesNo
ConstructorYesNo
arguments objectAvailableNot available

this Keyword Difference (IMPORTANT) ​

Normal Function ​

js
const user = {
  name: "Dipak",
  greet: function () {
    console.log(this.name);
  },
};

user.greet();

Output:

js
Dipak;

Arrow Function ​

js
const user = {
  name: "Dipak",
  greet: () => {
    console.log(this.name);
  },
};

user.greet();

Output:

js
undefined;

Why? ​

Arrow functions do not create their own this.

They take this from parent scope.


4. Callback Function ​

A function passed as an argument into another function.


Example ​

js
function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

function done() {
  console.log("Completed");
}

greet("Dipak", done);

Output ​

js
Hello Dipak
Completed

Why Callbacks are Used ​

  • Async operations
  • Event handling
  • Timers
  • API calls

Example with setTimeout ​

js
setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);

5. Higher-Order Function ​

A function that:

  • Takes another function as parameter OR
  • Returns another function

Example 1 — Function as Parameter ​

js
function operation(a, b, callback) {
  return callback(a, b);
}

function add(x, y) {
  return x + y;
}

console.log(operation(2, 3, add));

Example 2 — Function Returning Function ​

js
function outer() {
  return function inner() {
    console.log("Inside inner");
  };
}

const fn = outer();

fn();

Common Higher-Order Functions ​

  • map()
  • filter()
  • reduce()
  • forEach()

6. IIFE (Immediately Invoked Function Expression) ​

A function that runs immediately after creation.


Syntax ​

js
(function () {
  console.log("IIFE Executed");
})();

Arrow Function IIFE ​

js
(() => {
  console.log("Arrow IIFE");
})();

Why IIFE is Used ​

  • Avoid global variable pollution
  • Create private scope
  • Execute code immediately

7. Pure Function ​

A function that:

  1. Gives same output for same input
  2. Does not modify external data

Example of Pure Function ​

js
function add(a, b) {
  return a + b;
}

Same input always gives same result.


Impure Function ​

js
let total = 0;

function add(num) {
  total += num;
}

This changes external variable.


Benefits of Pure Functions ​

  • Predictable
  • Easy to test
  • Better debugging
  • Used heavily in React

8. Closures (VERY IMPORTANT) ​

A closure happens when an inner function remembers variables from its outer function even after outer function execution is complete.


Basic Example ​

js
function outer() {
  let count = 0;

  return function inner() {
    count++;
    console.log(count);
  };
}

const fn = outer();

fn();
fn();

Output ​

js
1;
2;

How Closures Work ​

Step 1 ​

outer() runs.

js
let count = 0;

Variable is created.


Step 2 ​

outer() returns inner() function.

js
return function inner() {};

Step 3 ​

Even after outer() finishes, inner() still remembers count.

This memory behavior is called a closure.


Real-Life Analogy ​

Think of a closure like a backpack.

The inner function carries outer variables in its backpack even after the outer function is finished.


Why Closures are Important ​

Closures are heavily used in JavaScript applications.


Uses of Closures ​

1. Data Hiding / Private Variables ​

js
function counter() {
  let count = 0;

  return {
    increment() {
      count++;
      console.log(count);
    },
  };
}

const c = counter();

c.increment();
c.increment();

count cannot be accessed directly from outside.


2. React Hooks ​

Hooks like useState internally use closures.


3. Event Handlers ​

Closures help remember variables during events.


4. Currying ​

Advanced functional programming concept.


Interview Definition of Closure ​

A closure is created when a function remembers variables from its lexical scope even after the outer function has finished execution.


Important Interview Points ​


Function Declaration ​

  • Fully hoisted

Function Expression ​

  • Not fully hoisted

Arrow Function ​

  • No own this
  • Short syntax
  • Cannot be used as constructor

Callback Function ​

  • Function passed into another function

Higher-Order Function ​

  • Takes or returns functions

IIFE ​

  • Runs immediately after creation

Pure Function ​

  • Same input → same output
  • No side effects

Closure ​

  • Inner function remembers outer variables
  • Used for private variables and data persistence

© 2025 DDocs · Dipak's Documentation Guide