javascriptparametersundefinediife

Why do functions (especially IIFEs) sometimes declare “undefined” among their parameters?


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?


Solution

  • 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