Lorraine Bernard
Lorraine Bernard

Reputation: 13400

undefined in parameter function. when should it be used?

I saw some javaScript, like Backbone-relational written in this way:

( function( undefined ) {
    "use strict";
        // some code
})();

My question is: When should undefined parameter be used? Always or in special circumstances?

Upvotes: 2

Views: 152

Answers (2)

user342706
user342706

Reputation:

Most of the time when you see that pattern they are ensuring that 'undefined' is truly undefined. See how at the bottom they don't pass any arguments.

This is a self executing function and you can pass parameters to it.

(function(undefined) {  // no parameters are passed in so undefined is undefined.
 "use strict";

})(/*no parameters passed*/)

If your code is using undefined and you need to ensure that some other javascript library doesn't alter the meaning of undefined then you would want to use this pattern. However, this is not something that commonly occurs, it is just a safety net. For some reason in javascript 'undefined' can be set a value just like any other variable.

Upvotes: 1

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

In Javascript, undefined is not a special keyword. It is a regular, global variable.

If undefined gets changed by outside code, it can cause weird bugs. Some people declare an unused parameter in their function declarations of undefined so the function will have a variable called undefined with the known value of undefined.

var undefined in the function body does the same thing, but requires a few more bytes.

Upvotes: 2

Related Questions