Hoisting in Javascript
- Get link
- X
- Other Apps
"Java script putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local
Note : JavaScript only hoists declarations, not initialization. If a variable is declared and initialized after using it, the value will be undefined.
Ex :
num = 100; // Initialization
console.log(name) // 100
var num; // Declaration
console.log(name) // Undefined
var num = 100; // Declaration
Here only declaration will go on the top not initialization.
let Vs var
The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while variable declared with var has the global scope.
In the Javascript engine there are different types of space, when we creates variable using var keyword then that variable will be available in global space and crating variable using let keyword that variable will be not available in global space.
Why let variables is not Hoistable
Using let and const keyword, creating variables then that variable will available in temporal dead zone and all the temporal dead zone variable and functions will be not hoistable.
Ex :
1. Using Let
num = 100; //Initialization
let num; // Declaration -- // Throws Reference-error: Cannot access 'num' before initialization
2. Using Const
num = 100; //Initialization
const num; // Declaration --// Throws SyntaxError: Missing initializer in const declaration
Note: Creating variables in java script using let and const that variable will be not hoistable.
above example will valid for functions as well.
let Vs Const
Cannot update const variable. const variable means it is immutable but in case of object we can update property value of object.the properties of a const variable can change. That's because the entire object is not immutable. It just can't be reassigned entirely.
Ex : In case of Variable
const name = "Manohar";
name = "Manu";
Above example will through error
Ex:
const person = { name: 'Manohar', age: 25}person.age = 27Above example will not throw any error, here we are changing only property not object.
Creating Variable using let keyword then we can re-initialize that variables.
Ex :
let name = "Manohar";
name = "Manu";
console.log(name) //Manu
- Get link
- X
- Other Apps
Comments
Post a Comment