Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: undefined as a function parameter

On this page, it shows some example code, containing the following line:

var Subject = ( function( window, undefined ) {

What is the undefined as a function parameter?

like image 808
Mr Mikkél Avatar asked Oct 28 '15 05:10

Mr Mikkél


People also ask

Can I pass undefined to function JavaScript?

See, undefined is passed as argument, but not passed as a parameter when we invoke the function. So, inside the function the value of the variable undefined is (guaranteed) the original value of undefined .

Can we use function as a parameter in JavaScript?

Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.

How do you know if a parameter is undefined?

So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .

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.


2 Answers

This is used to prevent from overriding the value of undefined in non-strict mode.

In non-strict mode, the value of undefined can be override by assigning other value to it.

undefined = true; // Or any other value

So, using the value of undefined will not work as expected.

In strict-mode, undefined is read-only and assigning value to it will throw error.

In the code, the value to the last parameter is not passed, so it'll be implicitly passed as undefined.

var Subject = ( function( window, undefined ) {

}(window)); // <-- No parameter is passed for the last value
like image 91
Tushar Avatar answered Oct 11 '22 03:10

Tushar


That is done to make sure that undefined always is undefined. In JavaScript, since undefined isn't a reserved word but a regular variable, this would be allowed for instance:

 undefined = 2; // Assign a different value to undefined
 if (undefined == 2)  // Now this statement would be true

So in your case

var Subject = ( function( window, undefined ) {

They pass in window and use it , but then they don't pass a second value to the undefined parameter, thus undefined will be undefined.

like image 25
Shailendra Sharma Avatar answered Oct 11 '22 04:10

Shailendra Sharma