Html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<input type='button' name='test' id='test' value='Click'/>
</body>
</html>
Javascript
$(document).ready(function(){
$('#test').on('click',function(){
var a = 10;
testFunction(a);
});
});
function testFunction(a,b){
alert(a);
}
Here when i click the Click button it alerts 10.But in the function call i have only one argument and in the function definition i have two arguments.So why it alerts the value instead of producing any errors regarding the number of arguments.?
4 Answers 4
That is because in Javascript the arguments are optional.
They have a default value so in pseudo code it would be
function testFunction(a = undefined,b = undefined){
alert(a);
}
Comments
Arguments in JS are dynamic, if an argument has been defined but not passed in nor used within the function then it won't throw error. If you want to check that there are at least 2 arguments you can do this:
function test(a,b) {
if (arguments.length < 2) {
// throw error, or return false, or something else
}
}
You can even use arguments that are not defined in the function through the arguments pseudo array. The number of arguments is determined when you call the function, not when you create it.
Comments
Arguments aren't required unless you make it that way. JavaScript is dynaic so arguments that aren't used get ignored.
function testFunction(a,b){
if (b == undefined) throw new Error("Variable b in testFunction is undefined");
alert(a);
}
Comments
In Javascript the arguments as listed in the function definition are the named arguments. They are however optional. So it is entirely possible to call your function like this:
testFunction(1);
testFunction(1, 2);
testFunction(1, 2, 3);
In the first case the value of argument b will be undefined.
In the third case there will be no variable receiving the value 3. However it is still there. All values passed into the function are accessible through the arguments array. So arguments[2] will contain the value 3.
Given this flexibility there is also a drawback. Unlike in many other programming or scripting languages there is no function polymorphism in Javascript. That means that there can only be 1 function with the same name. So you can't define 2 functions like this:
function testFunction(a, b) { ... }
function testFunction(a, b, c) { ... }
You can find more information on Javascript functions all over the internet, but this page is a good start: http://javascript.info/tutorial/arguments
testFunction(a,b,c){ alert(a); }. And try to debug with firebug. Instead of your first function this will get triggered.