Hoisting and Currying in JavaScript

Suman Kunwar
2 min readJan 22, 2023

--

Hosting is a default behavior in JavaScript of moving declarations at the top. While executing a code, it creates a global execution context: creation and execution. In the creation phase, JavaScript moves the variable and function declaration to the top of the page, which is known as hoisting.

// variable hoisting
console.log(counter);
let counter = 1; // throws ReferenceError: Cannot access 'counter' before initialization

Although the counter is present in the heap memory but hasn't been initialized so, it throws an error. This happens because of hoisting, the counter variable is hoisted here.

// function hoisting
const x = 20,
y = 10;
let result = add(x,y); // ❌ Uncaught ReferenceError: add is not defined
console.log(result);

let add = (x, y) => x + y;

Here, the add function is hoisted and initialized with undefined in heap memory in the creation phase of the global execution context. Thus, throwing an error.

Currying is an advanced technique in functional programming of transforming a function with multiple arguments into a sequence of nesting functions. It transforms a function from callable f(a,b,c) into callable as f(a)(b)(c). It doesn’t call a function instead it transforms it.

To get a better understanding of currying let’s create a simple add function add that takes three arguments and returns the sum of them. Then, we create a addCurry function that takes a single input and returns a series of functions with its sum.

// Noncurried version
const add = (a, b, c)=>{
return a+ b + c
}
console.log(add(2, 3, 5)) // 10

// Curried version
const addCurry = (a) => {
return (b)=>{
return (c)=>{
return a+b+c
}
}
}
console.log(addCurry(2)(3)(5)) // 10

Here, we can see that both the curried and noncurried versions returned the same result. Currying can be beneficial for many reasons, some of which are mentioned here.

  • It helps to avoid passing the same variable again and again.
  • It divides the function into smaller chunks with a single responsibility, making the function less error-prone.
  • It is used in functional programming to create a high-order function.

Note: To learn more about JavaScript visit https://github.com/sumn2u/learn-javascript.

--

--

Suman Kunwar

Innovating Sustainability | Researcher | Author of Learn JavaScript : Beginners Edition