Triple CCC: Currying, Closure, and Callback in JavaScript

This tutorial will teach you about the Triple CCC: Currying, Closure, and Callback in JavaScript. It’s almost 2023, and JavaScript is the most popular programming language in the context of web development.

If you want to build your career with this language, you need to have a solid understanding of its core concepts. The Triple CCC: Currying, Closure, Callback in JavaScript is something you’ll need to understand to ace your interviews. It will help you not only to gain knowledge about these topics but also give you an extra advantage in the interview. Because most of the time interviewers ask a common question from these topics.

Topics to be covered in this tutorial

We will cover the following topics in this tutorial and the topic’s names are given in the below section:

  • Function as First-Class Citizen
  • Currying
  • Closure
  • Callback
  • Conclusion

Function as First-Class Citizen

Before knowing about the CCC’s concepts, let’s explore a brief idea about functions in JavaScript and see how powerful it is. In programming languages, there’s a concept named First-Class Citizen that refers to passing, returning, and assigning a type. If a type is able to perform these actions then it will be considered the First-Class Citizen.

In the JavaScript language, a function can perform all the tasks and as a result, it is considered as the First-Class Citizen. Let’s see the below code example of JavaScript functions:

let addToNumbers = function(a, b) {
    return a + b;
}

let sum = addToNumbers(10,10);
console.log(sum);

// Output: 20

Here, you can see that we have declared a function and later on, we have stored it into a variable. This behavior is known as First-Class Citizen. This concept will help us to understand the following topics. Let’s start with the Currying in the next section.

Currying

The term currying is a programming paradigm or a pattern. More specifically, it is a pattern of functional programming and Haskell Curry invented this. Currying is used when we can break down multiple parameters of a function one by one.

It is a process of converting multiple parameter functions into a single parameter function. We will understand the concept of currying by solving the most popular interview question. Let’s see the question first.

function multiply(x, y, z){
  return x * y * z
}

console.log(multiply(5, 5, 5))

// Output: 125

In the interview, you may get this type of question and the task you need to perform is to call this function like multiply(5)(5)(5) this instead of multiply(5, 5, 5) this. How can you perform this action? Just to let you know – the answer is simple, it’s called currying. See the below code example:

function multiply(x){
    return function(y){
        return function(z){
            return x * y * z
        }
    }
}

console.log(multiply(5)(5)(5))

// Output: 125

In the question, there were three parameters in a single function. We simply break down those parameters and convert them into a single parameter function.

It is only possible because of the functional programming behaviour where we can call a function inside another function and can create a function chaining. The result is the same but now we are using the currying pattern to get this output

Closure

One of the most important concepts of JavaScript is closures. In simple terms, a closure is an act of closing. In JavaScript, closure is a function that references variables in the outer scope from its inner scope.

Before understanding closure, we need to know about the scope of a variable. A variable has three potential scopes, depending on where it is defined. It can have local, global, or block scope (you can read more about lexical environment in our article Effective JavaScript - 10 JavaScript Concepts You Should Know).

When a variable is declared inside a function it will be the local scope of that function. See the code snippet:

function demoFunc(){
  let val = 10
  return val + val
}

Here, the val variable is in the local scope and its lifetime will exist until the function is called. On the other hand, when a variable is declared outside of the function, it will be the global scope and it will represent the browser’s window Object if it is declared with var. See the below code snippet:

let val = 10

function demoFunc(){
  return val + val
}

This time the val is in the global scope and it will exist until the page has been removed. The concept of closure is used to make a global variable into a local one.

Let’s see the problem that closure solves in the below section and by doing so, you will be able to know why we need to learn the concept of closure in JavaScript.

function sayHello(){
    let name = 'John'

    function inner(){
        console.log(`Hello ${name}`)
    }

    return inner
}

let abc = sayHello()
console.log(abc)

// Output:
// [Function: inner]
// Hello John

Here, you can see that we are getting the output as expected. But the main question is how we are getting this? What is the reason behind it? Can you guess what actually happening here? Let’s break it down together in the below section:

At first, we declared a function named sayHello() and stored a string inside the name variable. Later on, we declared another function and print the name with a Hello message, and returned the inner() function. Finally, we have stored the returned function into the abc variable.

Now, when JavaScript executes the code it will not find the name variable as the sayHello() function’s memory has been destroyed. But how we are getting the output as expected?

The main reason behind this is that is the concept of closures. Here, it is true that the sayHello() function’s memory has been destroyed but it creates a reference of that function and as a result, while executing the inner() it can access the variable from the reference of the sayHello() function. To perform this action, you don’t need to write one line of extra code. Because the JavaScript engine is smart enough to perform this action. All you need to do is to understand the concept of closure and it is created by default every time when a function has been created in JavaScript.

Callback

In simple words, callback refers to the term call later. That means it refers to a function that will be called later. Let’s imagine a real-world scenario. Let’s say, we have an array that consists of fruit names. The array is saved in our database. We need to build a program that will add a new fruit and later on, print the fruit list with the newly added one. To perform this action we have written the below code:

let fruitNames = ['Apple','Banana','Orange']

function addNewFruit(name){
    setTimeout(function(){
      fruitNames.push(name)
    },5000)
}

function printFruits(){
    setTimeout(function(){
        console.log(fruitNames)
    },3000)
}

addNewFruit('Mango')
printFruits()

// Output:
// [ 'Apple', 'Banana', 'Orange' ]

Here, we have created a new feature that will add new fruit names. We have consoled it but there is no new fruit names have been added. The main reason behind this is the asynchronous behavior of JavaScript.

In JavaScript, if tasks take much time for completing, it will automatically keep them in the queue and look for those tasks which will take less time. In our code, this situation has occurred. As a result, we are not being able to get our desired result. So, how can we fix this situation? Before, going to the solution, try to think by yourself about the solution to it.

The answer to this problem is simple. All we need to do is to use the callback function so that we can break the asynchronous behavior of JavaScript and it can wait for us based on a specific task. Follow the below code example:

let fruitNames = ['Apple','Banana','Orange']

function addNewFruit(name, cb){
    setTimeout(function(){
        fruitNames.push(name)
        cb()
    },5000)
}

function printFruits(){
    setTimeout(function(){
        console.log(fruitNames)
    },3000)
}

addNewFruit('Mango',printFruits)

// Output:
// [ 'Apple', 'Banana', 'Orange', 'Mango' ]

We have already learned the Function is a First-Class Citizen in JavaScript at the beginning of this tutorial. Here, we have used that concept only. You can see that we have passed a function as the parameter of another function.

Now, when JavaScript executes the code, it will find that callback function and will execute it only after the previous functions have been executed. This concept is known as the callback and you can see that we have called this function after the previous function finished its tasks. That’s the reason we have mentioned Callback as Call later.

Conclusion

In this whole tutorial, we have covered three most essential concepts of JavaScript. That is also known as Triple C’s (Currying, Closure, Callback). If you have come this far then you may already know about these concepts. The purpose of this tutorial is to present these complex things in the easiest way.

There are many advanced concepts that have been built on top of the callback. You may often hear about the concept of callback hell, which is something of a nightmare for JavaScript developers.

You need to have a solid understanding of these topics, and to do so, keep this article as the reference for your learning and try to practice more based on these topics from different online sources. If you have any queries or confusion feel free to connect with me.

 This article was written by Niaz Khan, a professional technical writer and a developer with 2+ years of experience.

comments powered by Disqus

Related Posts

Unveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript

The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.

Read more

The Art of Data Visualization: Exploring D3.js

Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.

Read more

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more