javascriptfunctionparameterssignature

Why does JavaScript not treat missing function arguments as an error?


function Add(a, b) {
  /* … */
}

If we call this JavaScript function like Add(1), why do we not get an error even though we pass only the wrong number of arguments to the function? How does JavaScript treat the above scenario?


Solution

  • Javascript is a dynamic, weakly-typed language. As a result, it doesn't strictly enforce method signatures.

    Add is a Function object. It has a property called arguments which is an array-like object that contains the parameters that you pass in. As a convenience, it will also create local variables called a and b and assign the first and second elements in arguments to them. In the case where you only have one input parameter, b will be undefined.

    So, Javascript will treat

     Add(1)
    

    and

     Add(1, undefined)
    

    as almost identical. The difference here is that the arguments variable will be of length 2 instead of 1. From a purely pragmatic standpoint, though, they're pretty well the same.