36
Advanced JavaScript Series - Part 3: Weird JS behavior, Strict Mode and Hoisting

50
50
In the code sample, we didn't even explicitly declare the variable but we are able to use without any error and it is available in global scope
var
, let
or the const
keyword.Declaration example-
"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
7.Prevents us from deleting an undeletable property.
"use strict";
delete Object.prototype; // This will cause an error
8.Prevents us from using Octal numerical literals and Octal escape characters. Example-
"use strict";
let x = 010; // gives error
let x = "\010"; // gives error
Note- The "use strict" directive is only recognized at the beginning of a script or a function.

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
This code does not work because initializations are not hoisted. It returns
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"
This is because variable initialization using
let
or const
don't get hoisted.All codes implemented using JS Fiddle
36