Computer >> Computer tutorials >  >> Programming >> Javascript

How to prevent duplicate JavaScript Variables Declaration?


To prevent duplicate variable declaration in JavaScript, wrap your variable declaration with a function expression:

(function(){
   var rank = 1;
}())

The above code prevents your variable from other variables and functions. This won’t effect other global variables outside the function.

You variable rank won’t be visible outside the function, so whatever code you write for the variable should be inside the function.