For the following code, as I have redeclared a
with var a
, my expectation for alert(a)
is to show undefined
, but why it shows 4
?
function f(a) {
var a;
alert(a);
}
f(4);
For the following code, as I have redeclared a
with var a
, my expectation for alert(a)
is to show undefined
, but why it shows 4
?
function f(a) {
var a;
alert(a);
}
f(4);
In JavaScript, a variable is either global or local to a function. There is no such thing as nested scopes within a function (unless you actually nest one function inside another function).
Quoting Mozilla's JavaScript docs:
Since both the function parameter a
and your var a
are declared in the same function scope, they resolve to the same variable.
See also: What is the scope of variables in JavaScript?
Note that object fields can also sort of be considered another level of scoping—but that isn't really relevant to your question.
Also—as torazaburo points out in his comment below—ECMAScript 6 introduced a let
keyword, which lets you create true nested scopes within functions. However, this feature is new enough that I didn't originally consider it worth mentioning (since it's not really safe to use in production code just yet). E.g., it looks like Firefox won't officially support the new let
construct until their new release at the end of this month (January 2016).
Declarations are moved to the top of their scope in a process called hoisting.
For example:
var a = 5;
var a = 6;
var a;
becomes something like
var a = undefined;
a = 5;
a = 6;
a;
Therefore, attempting to redeclare an already declared variable without using any assignment does nothing.
In your case, the variable a
is already declared as a parameter of the function. So var a;
is useless. If you want to set it to undefined, use a = void 0;
.