6

Let's say I've defined a function :

function myAwesomeFunction(x){
    console.log(x);
}

now, what I expect is, if I'll call it like this: myAwesomeFunction(1) or myAwesomeFunction('lol') or myAwesomeFunction('whatever'), it'll work and it does.

but how does it work, even when I pass extra arguments to the function and simply ignores all arguments except the first one :

myAwesomeFunction('why so', 'serious?')

we don't even have any optional arguments in the above function?(i.e, like (x, y=''))

function myAwesomeFunction(x){
    console.log(x);
}

myAwesomeFunction(1);
myAwesomeFunction('lol');
myAwesomeFunction('whatever');
myAwesomeFunction('why so', 'serious?')
myAwesomeFunction('why', 'so', 'serious?')
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39

2 Answers2

6

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.

Javascript treats your parameters as an array. More specifically it's the arguments array, Named parameters in function declarations are just pointers to members of arguments. More info here

kemotoe
  • 1,730
  • 13
  • 27
0

When you defined the function, you gave it one parameter x

The language is designed to look for a single argument for each parameter, and ignore the others.

However, you are able to access the other arguments via the special arguments object.

Try typing console.log(arguments) within your function body and seeing what happens...

Faisal
  • 139
  • 7