Today I Learned - Rocky Kev

TIL what Single Threaded & Non-blocking means in JS

POSTED ON:

TAGS:

Javascript is a single-threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. So if we print from 1to 5 it will execute every line one by one and can’t execute all prints at a single time.

Let's use a real example:

console.log("started");

const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';

fetch(url).then(() => {
console.log("data fetched");
// return response.json();
})

console.log("ended");

In Javascript, the result will be:

started
ended
data fetched

What actually happens is for async calls, they get added to the queue and is revisited AFTER the stack is cleared (after the code goes from top to bottom).

In blocking languages, like C, or PHP, it will instead be:

started
(going out to fetch the data)
data fetched
ended

via What does Single Threaded & Non-Blocking mean in JavaScript?


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.