Callback functions in Javascript

Callback functions in Javascript

Introduction

So today we will learn about Callback functions in javascript. If you’re familiar with programming, you already know what functions do and how to use them. What when we talk about callback functions, They do one magical thing in javascript you must have used these functions but today we will learn how they magically change the behavior of javascript.

I will call you later✋

So functions in the javascript are the first-class function what does that mean?? It means the function can be passed as a function's argument, the function can return a function and the function can be stored as a value. The first-class function gives us the power that we can call other functions from another function🤯 we can also pass functions as parameters to other functions and call them inside the outer function. Sounds complicated? Let me show that in an example below

function takeFunction(callback){
callback()
}

function callback(){
console.log("i am callback function")
}

takefunction(callback);

print// i am callback function

See one more example-

function callback(){
console.log("i am callback function")
}

setTimeout(callback , 5000)

print// i am callback function

Try to understand, setTimeout in nothing but a function. It is taking two arguments, a callback function and a time. It will call this callback function after 5000 milliseconds. So this callback function will be called under the setTimeout function. so this is how the callback functions work.

Understanding how powerful callbacks are😋

So javascript is a synchronous, single-threaded language. What does that mean?? It means that javascript reads code top to bottom one by in a row and one thing at one time. Let's try to understand by example -

//javascript code

task 1
tasks 2 
task 3
.
.
.
.
.
.
task 100

So javascript will read code line by line means the task 1 and then task 2 then task 3 and so on....

, this is why we call it single-threaded language and this is known as synchronous programming.

but by the callback function, we can make javascript code asynchronous this is interesting right🥳 let's see an example-

//javascript code

task 1
function takeFunction(callback){
callback()
}

tasks 2 
task 3
.
.
task 50
function callback(){
console.log("i am callback function")
}
.
.
.
.
task 100
takefunction(callback);

So now I can call this callback function asynchronously🤯 this is amazing, isn't it? Haha I know we all have done this multiple times but now we know who callback functions help us to create such great things.

I hope you guys must have understood what is the callback functions in javascript, I hope we will learn more things in the future, So till then.......Happy learning✌