1
$(function() {
    foo1("text");
    foo2("text");
}) 

function callback(func) {
    func();
}

function foo1(bar) {
    callback(function() {
        console.log(bar);       // "text"
        bar = "derp";
        console.log(bar);       // "derp"
    })
}

function foo2(bar) {
    callback(function() {
        console.log(bar);       // undefined
        var bar = "derp";
        console.log(bar);       // "derp"
    })
}

Why is that declaration of var bar = "derp" undefining the parameter, that is accessed beforehand?

xDreamCoding
  • 1,654
  • 1
  • 12
  • 18

1 Answers1

2

Because this code

function foo2(bar) {
    callback(function() {    
       console.log(bar);       // undefined
       var bar = "derp";
       console.log(bar);       // "derp"
    })
}

is actually

function foo2(bar) {
    callback(function() {  
       var bar;
       console.log(bar);       // undefined
       bar = "derp";
       console.log(bar);       // "derp"
    })
}

due to the variable hoisting. So even if you created a global bar variable inside the foo1 call, a scoped variable bar is declared inside the inner scope of the foo2 function. That's why the first console.log returns undefined

See also Variable hoisting on SO

Community
  • 1
  • 1
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thanks.. "Hoisting" was the keyword here. That's really some unexpected behaviour if you never came in touch with it. – xDreamCoding Apr 22 '15 at 08:39
  • 1
    @xDreamCoding— "hoisting" is misleading jargon. Variable and function declarations are processed on entering an execution context and before any code is executed. Variables declared with *var* are initialised to *undefined*, therefore reading their value before assignment of a different value returns the value *undefined*. – RobG Apr 22 '15 at 09:13