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

后端 未结 8 2122
余生分开走
余生分开走 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:51

    Nothing will happen- meaning you won't get an error or a warning as passing the parameters in javascript is optional.
    All the parameters that weren't "supplied" will have the undefined value.

    function foo(x, y, z){
        //...
    }
    
    foo(1);
    

    Inside the foo function now:

    function foo(x, y, z){
        x === 1
        y === undefined
        z === undefined
    }
    

    You can even pass more arguments, like:

    foo(1,2,3,4,5,7); // Valid!
    

    You can know the amounts of parameters supplied by arguments.length from inside the function.

    function foo(x, y, z) {
        console.log('x value: ' + x);
        console.log('y value: ' + y);
        console.log('z value: ' + z);
        console.log('Arguments length: ' + arguments.length);
    }
    console.log('Zero parameters');
    foo();
    console.log('Four parameters');
    foo(1, 2, 3, 4);

    Example of useful function that handle any amount of parameters:

    function max() {
        var maxValue = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            if (maxValue < arguments[i]) {
                maxValue = arguments[i];
            }
        }
        return maxValue;
    }
    
    alert(max(1, 5, 7, 2, 88, 32, 44));

    0 讨论(0)
  • 2020-11-29 18:59

    Because there's no error until the function expects to be able to work with the parameter that you're supposed to pass.

    For example:

    function myfunction(x) {
        return x*2;
    }
    

    Would throw an error; albeit probably only a NaN (in this case) or a variable is undefined.

    0 讨论(0)
提交回复
热议问题