Skip to content Skip to sidebar Skip to footer

Why Are Arguments In Javascript Not Preceded By The Var Keyword?

This may be a silly question, but why are function arguments in JavaScript not preceded by the var keyword? Why: function fooAnything(anything) { return 'foo' + anyThing; } And

Solution 1:

Most dynamicaly-typed programming languages don't have explicit vars in the argument list. The purpose of the var keyword is to differentiate between "I am setting an existing variable" and "I am creating a new variable" as in

var x = 17; //new variable
x = 18; //old variable

(Only few languages, like Python, go away with the var completely but there are some issues with, for example, closures and accidental typos so var is still widespread)

But in an argument list you cannot assign to existing variables so the previous ambiguity does not need to be resolved. Therefore, a var declaration in the arguments list would be nothing more then redundant boilerplate. (and redundant boilerplate is bad - see COBOL in exibit A)


You are probably getting your idea from C or Java but in their case type declarations double up as variable declarations and the cruft in the argument lists is for the types and not for the declarations.

We can even get away with a "typeless, varless" argument list in some typed languages too. In Haskell, for example, types can be inferred so you don't need to write them down on the argument list. Because of this the argument list consists of just the variable names and as in Javascript's case we don't need to put the extraneous "let" (Haskell's equivalent to "var") in there:

f a b =  --arguments are still variables,
         -- but we don't need "let" or type definitions
   let n = a + b in  --extra variables still need to be declared with "let"
   n + 17

Solution 2:

It would be a redundant use of the var keyword. Items that appear in the parentheses that follow a function name declaration are explicitly parameters for the function.

Solution 3:

The var keyword declares the scope of the variable. A function argument also introduces the scope for that argument. Hence there's no need for it, since it serves the same function.

Solution 4:

I think the question comes up because we're used to seeing function bla (int i) in many languages. The same, syntactically, as the int i; somewhere in the function body to declare a variable. The two ints are however not doing the same; the first defines the type, the second defines type and the scope. If you don't have to declare the type, the scope-declaration still needs to happen (which is why we have var in the second case) but there is no information needed in front of arguments.

Post a Comment for "Why Are Arguments In Javascript Not Preceded By The Var Keyword?"