2

I have just come across a function which accepts a parameter actually called 'undefined'. It is something like this:

(function($,undefined) {
    // Do something
})(jQuery);

Either I'm going crazy, or there is no logical reason for this to be here as, well, undefined is undefined is undefined. Please can someone confirm either way? Thanks.

ClarkeyBoy
  • 4,934
  • 12
  • 49
  • 64
  • Thanks to everyone for the answers and for pointing out that it's a duplicate - sorry about that. I had a search initially but all I found was about passing in undefined when calling the function. – ClarkeyBoy Nov 20 '17 at 15:35

1 Answers1

3

That is a classic trick to have an undefined variable to check against, typically:

if (someVar === undefined) {}

// instead of:

if (typeof someVar === 'undefined') {}

Notice that the wrapper IIFE does not pass any second argument, making the undefined parameter effectively undefined.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • What is the downside to using `if (typeof someVar === 'undefined') {}`? – Dan Mandel Nov 20 '17 at 15:23
  • 1
    just longer to type and usually not shorten by JS minifiers. – ghybs Nov 20 '17 at 15:23
  • @ghybs can't the value of `undefined` be changed and that's why `if (typeof someVar === 'undefined') {}` is occasionally recommended? – dimwittedanimal Nov 20 '17 at 16:01
  • 1
    @dimwittedanimal yes `undefined` was modifiable. The above trick shields against that, since it uses a locally scoped variable. `if (typeof somVar === 'undefined'){}` is not _occasionally_ recommended, it is the primary way of checking that. But you have plenty alternatives to achieve the same effect, provided you take some precautions. – ghybs Nov 20 '17 at 16:07
  • @ghybs Thanks! Missed/forgot that it was a local var. – dimwittedanimal Nov 21 '17 at 13:38