Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I call a Javascript function which takes parameters, without supplying those parameters?

What happens when I call a Javascript function which takes parameters, without supplying those parameters?

like image 886
Krummelz Avatar asked Dec 04 '09 12:12

Krummelz


People also ask

Can a JavaScript function have no parameters?

The functions have different structures such as parameters or no parameters and some function return values and some do not in JavaScript. The simplest of function is the one without an parameters and without return. The function compute its statements and then directly output the results.

Can you call a function without a parameter?

You can use a default argument in Python if you wish to call your function without passing parameters. The function parameter takes the default value if the parameter is not supplied during the function call.

What happens when you call a function in JavaScript?

Invoking a JavaScript Function The code inside a function is not executed when the function is defined. The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function".

What happens to any extra parameters passed in to a JS function?

You can call a Javascript function with any number of parameters, regardless of the function's definition. Any named parameters that weren't passed will be undefined.


2 Answers

Set to undefined. You don't get an exception. It can be a convenient method to make your function more versatile in certain situations. Undefined evaluates to false, so you can check whether or not a value was passed in.

like image 170
KP. Avatar answered Sep 30 '22 18:09

KP.


javascript will set any missing parameters to the value undefined.

function fn(a) {     console.log(a); }  fn(1); // outputs 1 on the console fn(); // outputs undefined on the console 

This works for any number of parameters.

function example(a,b,c) {     console.log(a);     console.log(b);     console.log(c); }  example(1,2,3); //outputs 1 then 2 then 3 to the console example(1,2); //outputs 1 then 2 then undefined to the console example(1); //outputs 1 then undefined then undefined to the console example(); //outputs undefined then undefined then undefined to the console 

also note that the arguments array will contain all arguments supplied, even if you supply more than are required by the function definition.

like image 37
barkmadley Avatar answered Sep 30 '22 19:09

barkmadley