nitendra jain
nitendra jain

Reputation: 453

Why does JavaScript not treat missing function arguments as an error?

function Add(a, b) {
  /* … */
}

If we call this JavaScript function like Add(1), why do we not get an error even though we pass only the wrong number of arguments to the function? How does JavaScript treat the above scenario?

Upvotes: 3

Views: 369

Answers (2)

Shraddha
Shraddha

Reputation: 884

It is because of the concept of Hoisting in Javascript. Before the actual execution of your Javascript code, the parser runs through your code and it recognises where you have created the functions and where you have created the variables. Before your code begins to be executed by Javascript Engine - line by line, the Javascript engine already sets aside spaces in memory for the variables and functions written in the code. So, all the variables and functions are already made available in memory before your code execution begins. So, we will have access to them in a limited way.

When the Javascript Engine finds a function in your code, it sets up a memory space and places the entire function definition in it.

But, when it finds a variable in your code, it sets up a memory space; give it the name of the variable and sets a placeholder i.e. ‘undefined’ as its value (instead of the actual assigned value).

Please, have a look at the link below to have a better understanding of what is happening - https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

Upvotes: -1

Dancrumb
Dancrumb

Reputation: 27579

Javascript is a dynamic, weakly-typed language. As a result, it doesn't strictly enforce method signatures.

Add is a Function object. It has a property called arguments which is an array-like object that contains the parameters that you pass in. As a convenience, it will also create local variables called a and b and assign the first and second elements in arguments to them. In the case where you only have one input parameter, b will be undefined.

So, Javascript will treat

 Add(1)

and

 Add(1, undefined)

as almost identical. The difference here is that the arguments variable will be of length 2 instead of 1. From a purely pragmatic standpoint, though, they're pretty well the same.

Upvotes: 4

Related Questions