Mastering JavaScript: Understanding Callbacks and Higher-Order Functions

Mastering JavaScript: Understanding Callbacks and Higher-Order Functions

What is callback?

Let’s simplify this word callback for you it’s a function and also you can say it’s a arrow function which is being passed as an argument in a function parameter.

Example:

function foo(name,age){
/* 
     1. function -> is a keyword to decalre a function 
     2. foo -> i'm assigning a name to the function declaration
     3. (name,age) -> this like you are saying what the input will 
                      function take on the time of it call.
     4. here name and age are the parameters of the function .
*/
}

foo("Sourav",23) 
/* here "Sourav" and 23 are arguments for the function foo
 so it will be git mapped like name->"Sourav" 
and age->23 in function local memory.*/

The parameter is the name of the values which function takes while we call it and arguments are like the values the function take while we call the function which having parameter.

If you don’t understand don’t worry we will go deeper into it in the upcomming topics

Scope ?

Scope refers to what you can access in the current environment. To understand scope better, think of a subscription system on YouTube. A user with a premium subscription can use all the features available to free users, plus some extra features like downloading videos, picture-in-picture, background play, and YouTube Music Premium. However, a normal user can only access the free features and cannot use the premium ones. Scope works similarly: you can't see deeper into it, but you can see upwards from a deeper level, like looking through a tinted window.

Example:

let outer = 10;
function doStuff(){
    let inner = 20;
    console.log(outer);
    console.log(innner);
    /*
    -> inside the function you can see the outer and inner.
    */
}

/*
    but here is the piviot that outside of the function you can't see the innner varriable 
    the {} works like a wall where you can see from inside of the {} but 
    you cant see throught the {} outside of the {}.
*/
doStuff() // will log - > 10 20
console.log(inner); // throws an error : ReferenceError: innner is not defined

How does this code works from inside 🤔?

So as you know javascript is a single treaded language (this programming langage can only so one work ata time). Javascript mostly works on a concept :

  1. Thread of execution

  2. Memory

Thread of execution:

This you can say run code line by line.

Memory:

Ahh! by running the code linke by line also track the variables.

I userstand this works but why this is throwing Reference Error?????

Lets begin ;

  1. Line 1: let outer = 10; → This code tells JavaScript to create a memory space to store the value 10 and name that memory reference "outer." After this, JavaScript responds, "Got it, master!"

  2. Line 2: function doStuff(){ let inner = 20; console.log(outer); console.log(inner); } → "Hey JavaScript, do one more thing for me. Remember this code inside the {} and execute it whenever I ask for doStuff." JavaScript replies, "Okay, master, I did it."

  3. Line 3: doStuff() → "JavaScript, have you heard about doStuff?" JavaScript says, "Yes, master, it's a 3-line code." "Okay, JavaScript, execute it for me." JavaScript: "Okay, master, I did it. You asked me to remember 'inner' as the value 20 inside this function's memory, and then console.log() → print the value of 'outer' to the console. Oh! I got it, you told me to remember 'outer' as 10 from the global memory. Then I have to print 'inner' to the console, and its value is 20. Done, master."

  4. Line 4: console.log(inner); → "Hey JavaScript, just print the value referred to by 'inner'." JavaScript: "Master, I have never stored a reference with that name, so I don't have any reference to it."

Oh! I thought we were just writing code. No, no, we are having a wonderful conversation with the computer. Wow, that's amazing!

It’s important to remeber that whenever you run a function it will automatically creates it’s own memory inside and it will first look inside own memory and then search for global memory.

What is Higher Order Functions?

It's a bit strange and annoying, right? 😢 ... Hmm! If I tell you that you've been using these kinds of functions in string and array manipulations. Really! 🤔 No, no, no, you're lying. No, it's true! 😁😁

Hey, don't make it like rocket science, just keep it simple for me... 😢

Okay! If I tell you to take an array of 5 numbers and add 5 to each of them without using any built-in method.

It's so simple, man, see, I will do it this way!

const array = [1,2,3,4,5]

for(let i = 0; i<array.length; i++){
    array[i]+=5
}

console.log(array);

Ok! just multiply 20 on each element.

const array = [1,2,3,4,5]

for(let i = 0; i<array.length; i++){
    array[i]*=20
}

console.log(array);

Are we doing the right thing or making a mistake?

Yes, I did it, but maybe I'm repeating my code.

So, what should be done?

🤔🤔🤔 I got it! We need something that can take an array and decide what to do with it. But I have no idea how to do it…😢😢

Let me show you.

function add(number,value){
    return number + value;
}

function multiply(number,value){
    return number * value;
}

let array = [1,2,3,4,5]

function doItForMe(array,factory){
    let newArray = [];
    for(let element of array){
        newArray.push(factory(element,5))
    }
    return newArray;
}

console.log(doItForMe(array,add));
console.log(doItForMe(array,multiply));

So here is my approch of doing the same thing what you have done earlier . But notice what I avoid

  1. I didnot break the DRY rule

  2. I didnot mutate the array

Let's talk about what I did and how it works. Before diving in, let me give you an example to help you understand better. Imagine a candy factory (every child loves it 🥰). In a candy factory, there's a machine and some workers. You put raw materials into the machine, set the ratios, and the machine does the work. That's the basic idea of the factory. I used the same concept here. I treated the array as raw materials and used a factory method to decide what to do with them. This method returned a new, modified array, just like candies.

In a higher order function the function takes a function as an argument that’s it .

Let’s breakdown the steps to understand how it works !

Step 1: We declared a function, and JavaScript stored its code in global memory, called add.

Step 2: Next, we declared another function, and JavaScript did the same for multiply.

Step 3: We then declared an array called array and stored [1,2,3,4,5] in it.

Step 4: We declared a function called doStuff, and JavaScript stored its code in memory.

Step 5: We then used console.log to display the evaluated value of the expression doStuff(array, add).

Step 6: As we discussed earlier, whenever a function is called, a new block of memory context is created. We call this the execution context (the environment/context where the function code will be executed). Inside the execution context, let's first define the memory state.

## Local Memory
- array : [1,2,3,4,5]
- factory : function add
- newArray : []

Step 7 : As we go inside the for loop we go to each element in the varriable array and push the evaluated expression of factory(element,5) so as we dicussed earlier a new execution context will be created and let’s break down the memory status for the factory function ;

## Local Memory for first iteration
- number : 1 
- value : 5

Step 8 : as we all know what is the value of number + value i.e 6 and the 6 will be pushed inside the newArray and the add execution context will be cleared out. this step continues till the end of the array element.

Step 9 : at the end we return the value which the newArray refrence to will be returned by the function doStuff and the console will printed with [6,7,8,9,10].

Step 10 : Same process goes for the next console log .


💡
This is the whole stuff going under the hood of the higher order function and I tried my best to put my understanding on this hope you would able to match it up and anything missed or any suggesstion you want to give free feel to reachout and comment under this blog I will be happy to hear from you . These are the stuffs from my mentor Will Sentance From CodeSmith and free feel to check out their course on this called JavaScript: The Hard Parts, v2 available on Frontend Masters .