Experience, DotNet, Solutions

One of the key concepts of every programming language is the Scope. In JavaScript, variable and function scope is a little bit different and so cool! you can have multiple var (variable) in a function, All of them run well if you declare at the top of the function. (although you won't get any kind of error if you declare at the end of the function) For example:

As you can see, the value of x changed during the scope and finally, the changed value returned. So in JavaScript, scope affects the outer of its own. Now if you change the above code as a function scope, the output will be different:

The value of x(I mean "another thing) is in the scope of Test function only. so functions create a new scope in JavaScript and block is not a scope just like C#, C++, …

There is another interesting feature in JavaScript, which is about the variable declaration. Take this:

(function () {
var a = 1;
alert(a + " and " + b );
var b = 2;
})();

as I mentioned It’s not a syntax or compile error, but if you run this function it will alert "a and undefined". in these cases you should just hoist the variable, Hoistingis the act of moving the declarations to the top of the function. And you should move them on top! the JavaScript looks ahead to find all the variable declarations and hoist them to the top of the function. Variables in JavaScript are hoisted, it means Rather than being available after their declaration, they might actually be available beforehand. So if you hoist the above function's variables, it would be like this:

(function () {
var a = 1;
var b = 2;
alert(a + " and " + b );
})();

Rather than variable hoisting, we have function hoisting too, for example:

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb
Read More