Last Updated: September 09, 2019
·
900
· nickjacob

using void 0 for your IIFE's

It's possible to have a module/someone accidentally set the value of javascript's undefined to something...not undefined -- it's not a constant. So how do you get your undefined back? void(0):

undefined = 'pizza'; // all your code is breaking!!!
console.log('pizza'); // work of an evil developer
(function(undefined){
     console.log(undefined);
     // all the code in here is safe! Closures rule!
 })(void(0));

void always evaluates the expression in its brackets and then returns undefined. Since 0 evaluates to just...well...nothing, all void(0) does it return undefined! :)

1 Response
Add your response

The void expression isn't necessary: the anonymous function scope instantiates a new undefined argument, and not supplying anything is terser than using void:

(function(undefined){
     console.log(undefined);
     // all the code in here is safe! Closures rule!
 })();

But if, like me, you're really not keen on closing parentheses lines away from their opening counterpart, void is useful as a way of executing a closure (without that pair of parentheses!):

void function(undefined){
     console.log(undefined);
     // all the code in here is safe! Closures rule!
 }();

BTW void is an operator, not a function, so you don't need the parens — you can just write void 0 :)

over 1 year ago ·