+ 1

Question is on JavaScript function. Can anybody answer this.

//case 1) function hello(x) { alert("hello" + x); } hello(3); //output: hello3 //Case 2) function hello(x) { alert("hello" + x); } hello() //Output: helloundefined. case 3) function hello() { alert("hello" + x) } hello(3); //Output: error //case4) function hello() { alert("hello" + 3); } hello(3); //Output: hello3 //Why in 4th case it gives output unlike 3rd case.

23rd May 2020, 12:30 PM
Ajitha G R
Ajitha G R - avatar
8 Antworten
+ 1
Javascript does not care about function signature, you can pass any number of arguments to a function even if they are not in the function definition. they will just be undefined.
23rd May 2020, 12:54 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 5
look at the alerts of case 3 and case 4
23rd May 2020, 12:36 PM
ODLNT
ODLNT - avatar
+ 4
Because you don't have an undefined variable being passed to the alert function. That's why you don't have an error.
23rd May 2020, 12:49 PM
ODLNT
ODLNT - avatar
+ 2
Because in 3rd you are giving a value to parameter which is not declared in your function ,while in 4th try only alert("hello"+3); Without declaring a function u will get hello3 as o/p
23rd May 2020, 2:51 PM
Išhwäŕÿā.P 👑
Išhwäŕÿā.P 👑 - avatar
+ 1
case 3 // x has to be defined somewhere since it's not passed to the function.
23rd May 2020, 12:40 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
case 3 alert depended on param x (x not defined) case 4 alert not depended on any param
24th May 2020, 8:26 PM
george
george - avatar
0
ODLNT I know .But I want reason.. why it is giving output in 4th case
23rd May 2020, 12:42 PM
Ajitha G R
Ajitha G R - avatar
0
ODLNT Bahha🐧 Okay understood. so ,if function doesn't have any argument, calling function may contain argument and gives result only if [alert box or codes]contains undefined variable.? I thought it shows error .
23rd May 2020, 12:55 PM
Ajitha G R
Ajitha G R - avatar