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

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

    JavaScript doesn't have default values for function parameters like other languages do. So, you can pass as many or as little arguments as you want.

    If you don't pass a value, the parameter is undefined.

    function myfunction(x) {
        alert(x);
    }
    
    myfunction(); // alerts undefined
    myfunction(1); // alerts 1
    myfunction(1,2,3); // alerts 1
    

    If you pass more parameters than are in the signature, you can use arguments.

    function myfunction(x) {
        alert(x);
        console.log(arguments);
    }
    
    myfunction(1,2,3); // alerts 1, logs [1,2,3]
    

提交回复
热议问题