I am trying this simple addition in Javascript could someone please let me know why is it giving NaN as a result ?
function add(a,b,c)
{
z= a+b+c;
console.log(z);
}
add(10+10+10);
3 Answers 3
You define the function to accept three arguments and you are passing only one argument. As a result, the values of b and c are undefined in the function and adding undefined to a number results in NaN. Try this instead:
add(10, 10, 10);
Comments
You need to pass your arguments separately:
add(10, 10, 10);
The problem is that you've added the numbers before passing them to your function:
add(10+10+10);
adds together 10, 10 and 10, then passes it to the function, so really your code is:
function add(a,b,c) {
z= a+b+c;
console.log(z);
}
add(30);
Which will not work, because your function expects 3 arguments and only gets 1.
function add(a,b,c) {
// a is 30, b and c are both undefined
z= a+b+c;
console.log(z);
}
Comments
Add function expects 3 parameters. a, b and c. What you are doing now is passing an expression 10+10+10 which is not a valid number.
Try as following
function add(a,b,c)
{
z= a+b+c;
console.log(z);
}
add(10,10,10);