Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

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

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 not passing a parameter when the function demands it.

Sample function

function myfunction(x) {
    alert("This is a sample alert");
}

Now if I call the function myfunction(); I am presented with the alert. Why is that that I am able to call the function without any errors or warnings when I have not passed a parameter?

EDIT

I did not expect so many great answers and I am by no means in a position yet able to say which answer is the best so am I able to request people to suggest the best answer and I'll award the acceptance to that person.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...