Sunday, September 28, 2014

JavaScript: what result this will render

var data = 'mytest';
function showSomething() {
    console.log(data);    
    var data = 'newData';
    console.log(data);    
}

showSomething();
How about this:
var data = "Rafael Nadal";
(function () {    
    console.log("the guy was " + data);
    var data = "Roger Federer";

    console.log("the guy is " + data);
})();
JavaScript turns our function declaration into a function expression and hoists it to the top. JavaScript applies different rules when it comes to function hoisting depending on whether you have a function expression or a function declaration. A function declaration is fully hoisted while a function expression follows the same rules as variable hoisting.

JavaScript treats variables which will be declared later on in a function differently than variables that are not declared at all. Basically, the JavaScript interpreter "looks ahead" to find all the variable declarations and "hoists" them to the top of the function.

No comments:

Post a Comment