andrew.hedges.name / blog

Variable Hoisting Puzzle

November 27, 2012, 12:28 pm · Filed under: JavaScript

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 (hidden for suspense, click here to reveal!):


Short URL to this article: