2

I see the following pattern often:

(function (window, document, undefined) {
  // 
})(window, document);

undefined is expected but not assigned.

The Purpose is:

You have in any case a local variable undefined with the value 'undefined' (within the function-scope). Even when someone has overwritten the global variable undefined. This variable you can use in places where you want to have the value 'undefined' and exactly that makes me confuse.

Because there's the void-operator in JavaScript which serves exactly the use-case I've described above: To provide reliable the value 'undefined'.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void

So why use developer these undefined-pattern instead of the incorporated void operator?

ts248
  • 311
  • 1
  • 4
  • 11
  • I tend to use void 0 to represent undefined, but I never knew you could force a function expression with void until I clicked on that link. Nice! I'm also curious as to whether or not there's a good answer for this. – Dustin Stiles Mar 19 '16 at 08:40
  • I think the question was more about using the undefined keyword instead of void. As void 0 is equal to undefined and cannot be overwritten. So why would developers opt in to a pattern that was, by nature, unreliable? I don't think that post answers this question. – Dustin Stiles Mar 19 '16 at 08:43
  • @Dustin Stiles Yep, you're right. I would like to know why the pattern is used INSTEAD of the void-operator. I guess guys who use the pattern are familiar enough with the language to know that something with that purpose exists. – ts248 Mar 19 '16 at 10:07
  • Just using `undefined` is typically much more clear than `void …`. If you want the undefined value, why not call it that? This particular practice is only necessary when you are writing code for unknown environments where someone might have defined a `undefined`. Usually it just works without precautions. – Bergi Mar 19 '16 at 13:44

0 Answers0