JavaScript: single-threaded and synchronous
A few days ago single threaded and synchronous were just 2 heavy words for me. If this is you right now, don't worry I'll try my best to make you understand.
So, let's get started:
Single-threaded and synchronous are not that much different.
Single-threaded: It can do only 1 thing at a time and has a single call stack (don't worry just read and soon you'll get what it is)
Synchronous: As the name suggests synchronous means to be in a sequence. So, basically a function has to wait for the earlier function to get executed and everything stops until the wait is over.
The call stack is basically a data structure that records where we are in the program. If we step into a function we push it to the top of the stack and when we return a value from the function we basically pop the function off from the stack.
Let's understand it by running the below code:
function multiply(a, b){
return a*b;
}
function square(n){
return multiply(n)
}
function printSquare(n){
let squared = square(n)
console.log(squared)
}
printSquare(4)
👇See how the above code executes: There will be a main() function when the file starts executing then we call printSquare which gets pushed over the top of the stack which in turn calls a square function which gets pushed over at the top of the stack which in turn calls the multiply function which gets pushed over at the top of the stack.
Services IT Development Program Senior Associate | ServiceNow | IT Service Management
1y[Click to continue reading...] button is not working...!!!