JavaScript scope in functions vs Java scope in methods


For years, JavaScript to me was a mere validation tool or script for web applications. I hated it. I avoided using it.  This time JavaScript gets the same respect from me as Java does.  If you plan to “own” (or master if you can) JavaScript and you are coming from blocked-scoped languages like Java, C#, C and C++, this is one of key things you need to keep in mind:

In JavaScript, scope is kept within function, not within blocks (such as while, if and for statements).

n Java, declaring the same variable twice in a method causes a compilation error. But in JavaScript, this is allowed. This can lead to some problems if you are not too careful. For instance, you needed to create another variabe within a for loop but did not notice an existing variable with the same name several lines above. Below are JavaScript and Java sample codes.

Java and JavaScript Codes

In JavaScript, we can declare a variable twice in a function. This does not cause any compilation errors.  The most recent variable declaration and/or assignment will be used when the variable is used in the later parts of your codes. Below shows the output of running a JavaScript function.


In Java, you are not allowed to declare the same variable twice in a method. Doing so will cause compilation error.


There are other “traps” in JavaScript if you assume it works like Java, C or C#. Keep in mind JavaScript is different.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert