What would you expect when you ran the following code JS snippet ?
if (true) {
var x = 69;
}
alert(x);
Today I found out some interesting things about scope in JavaScript. At the moment I’m reading the book Secrets of the JavaScript Ninja and in the chapter I’m reading they are going back through the fundamentals of functions.
Here is one of the points made is around variables, functions and their scope:
- Variable declarations are in scope from their point of declaration to the end of the function within which they’re declared, regardless of block nesting.
- Named functions are in scope within the entire function within which they’re declared, regardless of block nesting. (Some call this mechanism hoisting.)
- For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.
The code at the top will actually alert 69 when run. This came as a bit of a shock for me because from my background of C# / Java I have always assumed x would have been out of scope due to the block level context of how those languages work. When executed i expected to see a healthy null alerted.
This whole time I have made the assumption that these same rules from my experience with C# applied with JavaScript. This realisation that part of the fundamentals of what I have learnt is a little flawed is a little humbling but it really opens your eyes to what you are re-learning and quite honestly it’s awesome.
I can’t believe I have been using JavaScript for so long and have never picked this up. I guess the situation never came up in anything I’ve written (or it has and no one has found it yet). Sure the situation would rarely come up and it’s not like what you are doing is wrong, you just don’t feel like an expert anymore and that’s the humbling part so it’s bitter-sweet.
The great thing is at the moment i feel like Neo (Matrix Movie) when he’s in the chair and Link just ran the procedure to push Kung Fu 1.0 into his head, this will definitely change the way i write JavaScript.
I guess its another notch on the sword on the way to ninja status….
Or maybe I’m just holding the sword the right way round now :)