JavaScript | PART II
What you don’t know about JavaScript | Part II
Let, Const and Var | Block Scope | Shadowing | Closure | Callback Functions | Event Loop
This is part II of the blog series “What you don’t know about JavaScript”. I suggest you to read my previous article (Things you don’t know about JavaScript | Part I) because the explanations written here will be directly related to the previous article.
Let, Const and Var
let, const, and var are the most frequently used keywords in JavaScript (JS) when variables are declared. JS engine stores var variables in its global context. But let and const variables are declared in separate memory space. So, let and const are not attached to the window object.
The temporal dead zone is the phase between hoisting and where that variable is assigned with a value. A let or const variable cannot be accessed when it is in the temporal dead zone. It will give a reference error. And another important aspect is that a let or const variable cannot be redeclared like var. In such a situation, a syntax error will be given. But what is the difference between let and const? The let can be declared and initialized at any point in the program. But const can only be declared and initialized in the same line. The value of const cannot be updated later in the code.
Block Scope
What is a block in JS? Simply, a block is a code that is enclosed by curly brackets. It will combine several statements and can be used instead of a single statement. Most commonly used with if statements, while or for loops.
1 {
2 var a = 10;
3 let b = 100;
4 const c = 1000;
5 }
In the above code, var will be declared in the global scope but let and const will be declared in a separate space related to that specific scope. So the variables let and const cannot be accessed outside the block.
Shadowing
1 var a = 1;
2 let b = 2;
3 {
4 var a = 10;
5 let b = 20;
6 console.log(a);
7 console.log(b);
8 }
9 console.log(a);
10 console.log(b);
What is the output of the above code?
Here var is declared in the global scope, so both line numbers 1 and 4 will be pointed to the same memory location. So, the output of both lines 6 and 9 will be 10. This is called shadowing. But let has a separate scope (block scope) for both its declarations. So, the output of line numbers 7 and 10 will be 20 and 2, respectively. And also, const works similarly to let.
Closure
Closure is a function with its lexical environment. Let me explain
1 function outer(){
2 var x = 1;
3 function inner(){}
4 }
The closure of the function inner is the function itself and the variables declared in the EC of outer. This closure concept is very useful in function returns. Let’s see some examples.
1 function outer(){
2 var x = 1;
3 function inner(){
4 console.log(x)
5 }
6 return(inner)
7 }
8 var t = outer()
9 t()
Can you guess the output of this code? It is clear that after the return statement the variable x no longer exists. Is it so?
JS functions when returned will hold its variables in the lexical scope of later. So, the output will be 1.
Callback Functions
We know that JS is synchronous, single-threaded language, which simply means that it can do one thing at a time in a specific order. From the previous knowledge, you know that functions can be passed on to another function as parameters. So those functions that are passed to another function are called callback functions.
function a(param1){
console.log(“A”);
param1()
}a(function b(){
console.log(“B”);
})
In the above code, we declare a function with a parameter param1. Then the function a is called and passed function b as an argument. In this case, A will be logged and then param1 is called, which will log value B.
Event Listeners
document.getElement(“buttonId”).addEventListener(“click”, function count(){
console.log(“Button Clicked”);
})
This basic code structure of an event listener will wait until a user clicks the button with the id buttonId and will log the value Button Clicked on to the console. So, with the previous knowledge of callback functions, you can identify the addEventListener method requires a string as the first argument and a callback function as the second.
Although our main focus in this article is on client-side coding, even the server-side environments such as Node.js uses events. I recommend you to explore that as well.
Event Loop
This is an important concept in JS. Most of the interview questions are based on the Event loop.
A browser is embedded with various Web APIs or Browser APIs such as local storage, timer, geolocation API, Canvas and WebGL for 2D and 3D animations, Document Object Model (DOM) API which displays web pages, a console, fetch, etc. The browser allows the JS engine to access these Browser APIs through a global object called the window.
window.console.log(“Event loops”);
But we never write window because the window is in global scope we can access it without keyword window.
console.log(“A”);setTimeout(function something(){
console.log(“C”)
}, 3000)console.log(“B”);
The above setTimeout function is called which is a Web API in the browser, passing a function as the callback and 3000ms as the second argument.
Initially, A will be logged on the console. Then setTimeout Web API will get the function and will wait for 3 seconds. You know that every function will create a separate EC in the call stack of the JS engine. This setTimeout will not create an EC because it is not a JS function but it is a browser API. It will be placed at a separate place in the browser. The execution continues and B will be logged on to the console and then the GEC will be popped from the call stack. Now, what happened to the setTimeout function?
SetTimeout should log C on to the console after 3 seconds. For that, it should be pushed onto the call stack because it is where the JS code is executed. This is where the callback queue and event loop comes in to picture. As soon as the setTimeout function expires, it will be pushed to the callback queue. callback queue follows first in first out. Then the responsibility of the event loop is to put the functions of the callback queue to the call stack once the call stack is empty. The event loop will always check the callback queue, once it finds a callback function in the callback queue it will push that to the call stack for execution.
Other than the callback queue, there is another queue which is known as the microtask queue. You can consider it as a queue, but with a higher priority than a callback queue. So, the event loop will push functions in the microtask queue first and then check the callback queue.
Apart from the above, there are many other concepts that are built around JavaScript. JS functions, function currying, this operator, and asynchrony in JS are some of the interesting concepts that you have to explore. Stay tuned for Part III.
References
MDN Web Docs
Namaste JavaScript by Akshay Saini