Pass undefined to the function expression that JavaScript calls immediately

Sometimes you can find old code in the wildundefinedPassed to the function. why?

I found this trick while watching a famous moviePaul Irish's video on jQuery source code.

This video is from a different era. It is 9 years old at the time of writing. Since then, the jQuery source code has changed, so you can't find the thing in it, but it still makes me very interesting.

In addition, JavaScript has also changed. This technique only applies to JavaScript before ES5.

This was almost a necessary step before ES5 was released in 2009.

Note: There is no need to add it to the ES5+ code base, because nowundefinedIs a read-only value.

Sometimes, in our code, we check variables in the following ways to see if they are undefined:

if (car !== undefined) {

}

If this is our code, and it runs on our own server that we control, it should work fine. But imagine that a library like jQuery needs to be tested in the field before it can work on every possible site.

If someone coversundefinedA simple

undefined = '🤔' //whatever value you prefer

Then aboveifWill fail, comparecarTo🤔.

This problem has been fixed in ES5, but it was possible before then.

in casecarActually it is uncertain, and the answer cannot be found now.

In addition to using this technique: we wrap all the code in IIFE (Function expression called immediately), and then pass a parameter to the function definition without adding it in the call phase.

(function() {
  /* our function code */
})()
(function(undefined) {
  /* our function code */
})()

Look,undefinedPassed as a parameter when calling a function, but not as a parameter. Therefore, the value of the variable in the functionundefinedIs the (guaranteed) original valueundefined. No matter what actions other scripts on the page perform, it is isolated.

Now, my favorite way to solve this problem is to use this technique to check for undefined values:

if (typeof car !== 'undefined') {

}

ThistypeofThe operator returns a string with variable type. We can compare'undefined'String, and we will not encounter the above problems in the first place.

However, it is always nice to know the reason for something that can be read on code written by other people, especially when it needs library-level code that runs anywhere.

Download mine for freeJavaScript beginner's manual


More js tutorials: