In older code, you may come across a situation where undefined is intentionally passed to a function. Why was this done?

I stumbled upon this interesting technique while watching the well-known Paul Irish video about the jQuery source code. This video is from a different era, being 9 years old at the time of writing, and the jQuery source code has since changed, so you won’t find this trick in there anymore. However, it’s still worth exploring.

It’s important to note that JavaScript itself has evolved since then, and this technique is only applicable to pre-ES5 JavaScript. Before ES5, which was released in 2009, this step was almost necessary.

Note: ES5 and newer codebases don’t need this anymore because undefined is now a read-only value.

In some codebases, we often check if variables are undefined like this:

if (car !== undefined) {

}

If this code runs on our own servers, which we control, it should work fine. But consider a library like jQuery that needs to work across various websites. If someone were to overwrite undefined with a different value:

undefined = '🤔' //whatever value you prefer

the above if statement would fail, comparing car to '🤔'. This was possible before ES5.

Once car becomes truly undefined, it becomes impossible to differentiate. However, there is a technique we can use to overcome this problem. We can wrap our code in an IIFE (Immediately-invoked Function Expression) and pass undefined as a parameter in the function definition, without including it in the invocation.

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

By doing this, undefined is passed as an argument but not as a parameter when invoking the function. Therefore, inside the function, the value of the undefined variable will always be the original value of undefined. Regardless of any modifications made by other scripts on the page, it remains isolated.

Now, my preferred way of addressing this issue is by using the following technique to check for undefined values:

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

}

The typeof operator returns the type of a variable as a string. We can check it against the string 'undefined', which eliminates the problem mentioned earlier.

It’s always beneficial to understand the reasoning behind certain techniques used in code written by others, especially when dealing with library-level code intended to run in various contexts.