What exactly JavaScript is?
Definition
JavaScript is a synchronous single-threaded scripting language that was initially meant to run on the client-side(web browsers). But nowadays, we can run JavaScript on the server-side as well.
But wait, What does it mean by synchronous and single-threaded?
Let's deep dive into it
Synchronous
In English, it simply means that something is happening at the same time. And in terms of programming language, it simply means the code will execute in order line by line.
EG:
console.log("one");
console.log("two");
console.log("three");
/*
The above code will execute in below order
one
two
three
*/
But, sometimes you might encounter some code that will run asynchronously in JavaScript.
EG:
console.log("one");
function magicFunction(){
console.log("It's magic");
}
setTimeout(magicFunction,5000);
console.log("two");
/*
The above code will output the below result
one
two
undefined
It's magic --> will display this after 5000ms.
*/
Now you would be wondering what the hell is happening, you just have read that JavaScript is a synchronous language??
Let's understand this more deeply why and how.
In the above example, setTimeout
will execute asynchronously.
But what if I tell you thatβ-β setTimeout is not a part of the JavaScript language itself instead it's a part of the browser's web API.
Some examples of browser APIs are fetch, setInterval, DOM methods etc.
To make JavaScript more powerful on the client-side, browser JS-Engine attaches browser APIs with JavaScript and it will work like normal JavaScript.
So it means JavaScript is a synchronous language only. There are some other wrappers around it that make JavaScript run asynchronously.
Okay, but what does it mean by single-threaded?
Single-thread
It simply means we have a single-thread or a callstack to execute a JavaScript code. And we should not block this thread or else your app will crash and you won't be able to perform another task while one task is executing.
In the above example, we saw that setTimeout
was running asynchronously.
But here it won't block the main thread. It will execute outside the callstack.
After timeout, callback function inside the seTimeout will wait in callback queue till the callstack gets empty.
An Event loop constantly keeps checking whether the callstack is empty or not. As soon as it gets empty event loop put callback function from callback queue to callstack and it gets executed.
And there you go ... π€π€π€
Now you know what exactly JavaScript is.
follow me for more such blog posts.
Let me know if this blog was helpful.