Reputation: 16792
I have a function like so
function foo(x){
if (typeof x === 'undefined'){
var x = 123;
}
}
is the var
statement necessary? JSlint complains that variable x hides argument
(probably b/c I am defining a variable in the scope of the if statement.
Upvotes: 2
Views: 476
Reputation: 5201
The var
is not necessary, and in fact it is a mistake. You should use var
to declare a new variable. Once the function has an argument x
it is declared - whether it is passed a value or not.
By the way, in such cases when you know the variable is declared but just don't know whether it's been assigned a value or not, you can write x === undefined
- using typeof
and a string comparison is not necessary.
Upvotes: 4
Reputation: 755259
No var
is not needed here and it's in fact very misleading. The var
modifier is used to scope a value to the current function scope. Hence it's most useful at the top of the method or at worst on the first usage of the value. Parameters are always scoped to the current function hence it has no value.
Using it for subsequent usages suggests it's the first use / declaration of the value. This can be misleading to future developers.
Upvotes: 4