andrew.hedges.name / blog

Variable Hoisting Puzzle

27 November 2012 · Estimated reading time: 2 minutes

My colleague, Kyle, recently sent around an excellent article on execution contexts in JavaScript. I’m a big fan of esoteric JavaScript puzzles, so here’s one for you. Hint: the answer is in the above-linked article!

Given the following…

(function(){
    alert(a)
}())

Run it

And…

(function(a){
    alert(a)
}(1))

Run it

And…

(function(){
    var a
    alert(a)
    a = 2
    alert(a)
}())

Run it

What do we expect the following to do, and why?

(function(a){
    var a
    alert(a)
    a = 2
    alert(a)
}(1))

Run it

I wasn’t surprised that Kyle—the person who sent around the article that prompted all of this—was also the first to answer this puzzle I sent in response. The following was his answer:

Click here to reveal

a is defined in the creation stage by the argument passed in (i.e. 1)
a then is redefined as 2 during the execution stage after the first console.log

And the var is ignored since the variable was already defined previously by the argument name. From the article:

if the property name already exists on the activation object, we simply bypass the declaration