Why are arguments in JavaScript not preceded by the var keyword?

后端 未结 4 428
萌比男神i
萌比男神i 2021-01-12 02:05

This may be a silly question, but why are function arguments in JavaScript not preceded by the var keyword?

Why:

function fooAnything(anything) {
  r         


        
4条回答
  •  误落风尘
    2021-01-12 02:32

    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
    

提交回复
热议问题