chris97ong
chris97ong

Reputation: 7060

javascript - Do additional arguments in a function affect it?

function a() { alert('"A" is called.'); }
var b = function() { alert('"B" is called.'); }

a(true);
a(false);
a();

b(true);
b(false);
b();

The above code creates 3 alerts saying that "A" is called, and then another 3 alerts are created, saying that "B" is called. Fiddle

I would like to know, in Javascript, do additional arguments in a function affect the function in any way?

Upvotes: 0

Views: 54

Answers (2)

hjing
hjing

Reputation: 4982

No. In fact you can also define a function:

var x = function(y) {
  alert("'X' is called with " + y);
}

and call it as x() without any parameters at all.

It will create an alert saying 'X' was called with undefined.

Inside functions you have access to its arguments in an array-like object called arguments.

See the "arguments" docs for more details.

Upvotes: 1

tomysshadow
tomysshadow

Reputation: 932

In Javascript, all variables passed to a function are optional. They will just be undefined. However, in your example, you have not put any variables in the brackets. If you want true/false to be passed to the function you will need to define it as "function a(b) {" with b being the variable you want to pass. Otherwise your boolean is ignored and the function just runs normally and ignores it.

Upvotes: 0

Related Questions