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:
console.log(variable); // undefined Var variable="something"; Now, notice about the following code: var x = "something "; console.log(x); // something if (true) { var x = "another thing"; console.log(x); // another thing } console.log(x); // another thing.
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:
var x = "something "; console.log(x); // something Function Test() { var x = "another thing"; console.log(x); // another thing }; Test(); console.log(x); // something
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, Hoisting is 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:
foo(); // TypeError , undefined foo2(); // defined Var foo=function(){ //operation }; Foo2(){ // operation };
We called the function (I mean foo2()) before the declaration. Notice that foo() is not a function at all in line 1 and function definition hoisting only occurs for function declarations.
Category: Software
Tags: JavaScript