You shouldn't use the var
keyword if you're changing the value of a variable that's already been declared.
So:
var x = 1;
if(something) x = 2;
If the test was that simple, you could also write it like this:
var x = something ? 2 : 1;
It's also got to do with scoping. A new scope is created within functions.
For example:
var x = 1;
function myFunction(){
var x = 2;
}
myFunction();
console.log(x); // 1
Whereas, if you omitted the var
keyword within the function, you would be altering the value of the x
variable in the outer scope and the console.log(x)
would show 2
.