What happens if I don't pass a parameter in a Javascript function?

后端 未结 8 2159
余生分开走
余生分开走 2020-11-29 18:19

I am new to the world of Javascript and am tinkering with writing very basic functions and stumbled upon the example below by accident and am unsure why it works when I am n

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 18:45

    That's just how JavaScript works. Parameters are optional, and will have the not-really-a-value value "undefined" in the function if they're missing from a function call.

    By "optional" I mean just that: invoking any function involves an arbitrarily long list of parameters. There need be no relationship between the number of parameters passed to a function and the number declared. Best way to think of this declaration, then:

    function x(a, b, c) {
      // ...
    }
    

    is that you're declaring a function and binding the name "a" to the first parameter, "b" to the second, and "c" to the third. It's by no means guaranteed, however, that any of those will actually be bound to a value in any given invocation of the function later.

    By the same token, you can define a function without any parameters at all, and then "find" them via the arguments object:

    function noArgs() {
      var a = arguments[0], b = arguments[1], c = arguments[2];
      // ...
    }
    

    So that's not quite the same as the first function, but it's close in most ways that count practically.

    The "undefined" value in JavaScript is a value, but it's semantics are kind-of unusual as languages go. In particular it's not exactly the same as the null value. Also, "undefined" itself is not a keyword; it's just a semi-special variable name!

提交回复
热议问题