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.
The
varis not necessary, and in fact it is a mistake. You should usevarto declare a new variable. Once the function has an argumentxit 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– usingtypeofand a string comparison is not necessary.