JavaScript Variable Scope confusion for Java Developers

February 16, 2013 in JavaScript, Web 2.0

Sometimes, the Java developers that are new to the JavaScript world have a confusion regarding the variable scoping in JavaScript. Let’s see an example that will illustrate this confusion, consider that we are having the following Simple JavaScript code:

<script>
var someVar = 0;

{
    var someVar = 100;
}

alert(someVar);
</script>

Some of the new JavaScript developers (from Java background) will expect that the result of the someVar will be 0, because the defined someVar variable inside the inline block will be ignored once the inline block ends.

In fact, the end result will be 100, This is because JavaScript does not have the concept of Java block scopes, JavaScript has only two scopes:
1. Global Scope.
2. Local Scope which is applied ONLY on the function(s) level (A single function or functions inside function) NOT on any other type of block(s) level (such as loops and inline blocks).

To be able to understand JavaScript local scope, Let’s introduce a new function to our original example:

{
    var someVar = 100;
    //someVar will be visible everyWhere ...
}

function someFunction() {
    var someVar = 10; 
	
    //someVar will be visible only here as 10 ...
}

alert(someVar);
someFunction();
alert(someVar);

The result will be:

100
100

someFunction defines a someVar variable and initializes it to 10, the someVar variable will be visible as long as we are in the someFunction's scope, when the someFunction ends, the someVar's function variable will not be available anymore, this is why the second alert will produce 100 which is the original value of someVar that is defined in the Global scope.

2 comments on “JavaScript Variable Scope confusion for Java Developers

  1. Harold Means on said:

    What happens if I use a number different from 100? If I put 0 in the top number and 100 in the bottom number they will be different right?

  2. @Harold: the result in this case will be 0. As long as you define a variable inside a function in JavaScript, this variable will be available only inside the function.

Leave a reply

Your email address will not be published. Required fields are marked *

336,742 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha