35
loading...
This website collects cookies to deliver better user experience
50
50
var
, let
or the const
keyword."use strict";
x = 3.14; // this will cause error
"use strict";
const obj = {get x() {return 0} };
obj.x = 3.14; // This will cause an error
"use strict";
delete Object.prototype; // This will cause an error
"use strict";
let x = 010; // gives error
let x = "\010"; // gives error
x = 5 // doesn't give any error because of hoisting
console.log(x)
var x // this gets hoisted to the top of the scope
5
console.log(hello()) // doesn't give any error because of hoisting
function hello(){ // this gets hoisted to the top of the scope
return "hello world"
}
"hello world"
let
and const
keywords are hoisted but not initialized meaning that the block of code is aware of the variable but cannot use it until it's been declared, thus they give error.x = 5
console.log(x)
let x
ReferenceError: Cannot access 'x' before initialization
x = 5
console.log(x)
const x
SyntaxError: Missing initializer in const declaration
All JavaScript declarations are hoisted but not for initialization. Initialization in variables using var
keyword are partially hoisted but those using let
or const
keyword are not hoisted at all and give error.
Partial hoisting means that the JS engine before running the code line by line already knows that the variable exists and has some memory allocated (because of hoisting) but the value for it hasn't been set/ stored yet (it gets set when we actually reach that line of code) thus undefined
is returned. This partial hoisting happens in case of variable initialization using var
keyword.
Credits- Sabih Rehman
console.log(x)
var x = 5 // this is initialization, not a declaration
undefined
undefined
because we have used var
here that leads to partial hoisting as discussed above.console.log(x)
let x = 5 // this is initialization, not a declaration
Uncaught ReferenceError: Cannot access 'x' before initialization"
let
or const
don't get hoisted.