function Foo(f) { var f = f; }
Here inside the function, variable f is local to the Foo (it has a function scope), but why is the variable f in the argument list not in conflict? Maybe because it is bound inside the Foo.arguments object?
In other languages we cannot declare an argument variable with the same name as a local variable.
How is this name ambiguity resolved? Or, How do you reference each of the two distinct f variables later in the method?
JavaScript does a couple of things that aren’t obviously intuitive – the one you’re interested in is called ‘hoisting’ – JS moves var declarations to the top of a function, where they serve the sole purpose of reserving this variable name as a local variable in the function’s scope. Sometimes, this leads to lots of weirdness. If the variable name is already reserved as a local variable (e.g. it’s an argument) the var declaration gets dropped entirely.
Another unintuitive part of JS is how it deals with argument variables and the
argumentsobject (which are a bit special, as Hippo showed). That’s not necessarily what you’re interested in, though – what’s important for your example is that arguments also declare that variable name as local to the function.The result of all this is that when you have a
var fas well as an argument namef, the `var f’ gets dropped, and your example is equivalent to:You can see this in Hippo’s example, because:
Is equivalent to:
Is equivalent to:
For more details, read up section 10.1.3 – Variable Instantiation (bottom of p.37) in ECMA-262, the JS specification.