Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'use strict' not stopping hoisting in function scope

My Problem Lies here I'm learning JavaScript But not new to Programming at all. I understand hoisting, but with strict mode shouldn't this produce an error and be caught either when 6 is assigned to undeclared a variable or document.getElement... is assigned x this doesn't produce an error so my diagnosis is that hoisting is still going on..which i don't like and want to get rid of with using strict. Using Chrome Version 42.0.2311.152 m as my browser

function strictMode(){
    'use strict';
    try {
        x = 6;
        document.getElementById('hoisting').innerHTML = x;
        var x;
     }
     catch(err) {
                    document.getElementById('error_report').innerHTML = 
                        "There was an error that occured (Were in Strict Mode)" +
                            " " + err.message;
               }
}
like image 783
Zach Hutchins Avatar asked May 31 '15 15:05

Zach Hutchins


People also ask

Does strict mode stop hoisting?

Strict mode prevents sloppy hoisting It introduces different semantics, such as eliminating some silent errors, improves some optimizations and prohibits some syntax, such as accessing variables before they've been declared.

How can we stop a function from getting hoisted?

Some ways to avoid hoisting are: Use let or const — As explained above, using let or const instead of var would throw an exception and not let the program run, hence helping catch the issue earlier. Use function expressions instead of function declarations.

Can hoisting work in function?

In JavaScript, hoisting is only done for variable and function declarations but not assignments. So, when a variable is assigned then hoisting doesn't work and gives a TypeError or a ReferenceError.

How hoisting affects the global scope?

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, 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.


1 Answers

Variable declarations (i.e. var x;) are valid for the entire scope they are written in, even if you declare after you assign. This is what is meant by "hoisting": the var x; is hoisted to the beginning of the scope, and the assignment x = 6; is fine because x has been declared somewhere in that scope.

Strict mode does not change any of this. It would throw an error if you omitted the var x; declaration altogether; without strict mode, the variable's scope would implicitly be the global scope.

In ES2015 (a.k.a. ES6), hoisting is avoided by using the let keyword instead of var. (The other difference is that variables declared with let are local to the surrounding block, not the entire function.)

like image 172
Thomas Avatar answered Oct 23 '22 00:10

Thomas