Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JSfiddle and Chrome console return different values of the same function?

I have the following code in JSfiddle.

var a = 1;

function five() {
    this.a = 5;
    console.log(a); //JSfiddle prints the value 1
}

five()

But when I paste the same exact code inside Chrome console, the function five() prints 5. Why?

like image 349
Zip Avatar asked Apr 13 '16 14:04

Zip


1 Answers

By default JSFiddle wraps your code in the window.onload event, so you're actually running this:

window.onload = function() {

    var a = 1;

    function five() {
        this.a = 5;
        console.log(a); //JSfiddle prints the value 1
    }

    five()

}

That means that a is local to that function, while this still refers to the global object (window). In the Chrome console, without the wrapper function, var a is creating a global variable, which are created and stored as properties on the global object, and is thus the same as window.a / this.a.

If you go to the JavaScript options and choose either of the "nowrap" options, it will log 5 in JSFiddle too:

enter image description here

like image 76
James Thorpe Avatar answered Oct 20 '22 02:10

James Thorpe