JavaScript Variable Scope confusion for Java Developers

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:

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:

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.