Search code examples
javascriptusingstricthoisting

'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;
               }
}

Solution

  • 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.)