Part-2
What are Callbacks in JavaScript?
- When you nest a function inside another function as an argument, that's called a callback.
Here's an illustration of a callback:
Why do we use callbacks?
When doing a complex task, we break that task down into smaller steps. To help us establish a relationship between these steps according to time (optional) and order, we use callbacks.
Take a look at this example:π
The shop will have two parts:
- The storeroom will have all the ingredients [Our Backend]
- We'll produce ice cream in our kitchen [The frontend]
Let's store our data
Now, we're gonna store our ingredients inside an object. Let's start!
let stocks = {
Fruits : ["strawberry", "grapes", "banana", "apple"]
}
You can store these other ingredients in JavaScript objects like thisπ¦π¦π§π¨,
The entire business depends on what a customer orders. Once we have an order, we start production and then we serve ice cream. So, we'll create two functions ->
- order
- production
let's establish a relationship between these two functions using a callback, like this: π
If you're wondering how we picked strawberry from our stock variable, here's the code with the format π
let production = () =>{
setTimeout(()=>{
console.log("production has started")
},0000)
};
We'll nest another setTimeout function in our existing setTimeout function to chop the fruit. Like this: π
result :
let production = () =>{
setTimeout(()=>{
console.log("production has started")
setTimeout(()=>{
console.log("The fruit has been chopped")
setTimeout(()=>{
console.log(${stocks.liquid[0]} and ${stocks.liquid[1]} Added)
setTimeout(()=>{
console.log("start the machine")
setTimeout(()=>{
console.log(Ice cream placed on ${stocks.holder[1]})
setTimeout(()=>{
console.log(${stocks.toppings[0]} as toppings)
setTimeout(()=>{
console.log("serve Ice cream")
},2000)
},3000)
},2000)
},1000)
},1000)
},2000)
},0000)
};
Result :
Feeling confused?
This is called callback hell. It looks something like this.
Take a break
we will learn about CallBack Hell in next Post.....
Happy Learning.















Top comments (0)