1) Scope:
Scope is that area in which values , expressions are visible , if u try to access any values , expressions out of it you wont be able to access it and will get reference error.
JavaScript has the following kinds of scopes:
Global scope
The default scope for all code running in script mode.
Module scope
The scope for code running in module mode.
Function scope
The scope created with a function.
In addition, variables declared with let or const can belong to an additional scope:
Block scope
The scope created with a pair of curly braces (a block).
function myFunction() {
let a = 2; // a can only be used in myFunction
console.log(a);
}
console.log(a); // Causes error
In the above example, we are not able to access variable a as it's declared using let which is a block-level scope and can only be accessed within the curly braces.
const a = 2;
exampleFunction();
function exampleFunction() {
console.log("Inside function");
console.log(a);
}
console.log("Outside function");
console.log(a);
In the above example, we are able to access variable a as its declare outside function and can be accessed anywhere throughout the program.
2) Single Thread
Javascript is a synchronous , single-threaded language which means it executes one task at a time and do it line by line.
A thread in computer science is just like executing multiple tasks or programs known as a thread.
function Outer(){
function Inner(){
}
Inner();
}
Outer();
In the above example execution of call stack is explained which shows how JS works single threadedly.
3) Call Stack
Call Stack is just a mechanism in Javascript in which it keeps track of multiple functions running in JS code.
Let's take the example and nail down the concept.
function Outer(){
function Inner(){
}
Inner();
}
Outer();
Steps how functions are pushed in call stack...
1st Step(Global Execution Context is created):
2nd step(Pushed Outer Function):
3rd step(Pushed Inner Function and popped Outer Function ):
Final step(Finally Call stack is empty):
4) Hositing
It is a concept in Javascript in which you try to access the variables and functions before they are initialized.
Steps How Hoisting Works :
The whole JS code is scanned and a global execution context is created in which variables , functions of code are made undefined, available respectively is known as Hoisting.
console.log(x);
getName();
var x = 10;
function getName() {
console.log("Get name");
}
As, soon as we execute the above program , the whole JS code is scanned , global execution context is created and variables(i.e x) is assigned undefined till the time any value is assigned to it and function(i.e getName()) is made available.
Here, x = undefined
Here function getName is made available:
So, Overall we have to remember 2 golden rules in Hoisting:
1) Variables declarations are scanned and made undefined
2) Function declarations are scanned and made available