Skip to content Skip to sidebar Skip to footer

What's A Good Use Of Void()

EDIT: To clarify: My question isn't concerned with how void is used but whether void can be really useful. I'm asking this because the way people seem to use it is very offputting.

Solution 1:

Use case #1, void(0): If you want a reference to the real undefined (and not just the variable, because it can be overwritten) you don't need void. You can get it like this instead: (function(){}()).

Use case #2, void(exp): If you want to execute code and then return undefined, you can of course do it by wrapping your code in a function: (function(){ exp; return undefined; }()).

So, no, we don't need void. It does nothing unique. It is shorter than the above solutions though, so if you prefer short and obscure code you could use it (but please don't).


Solution 2:

Jakob shows some practical use cases of void. However as he mentions void is not really required, but I use it to test for undefined. I use it to create my own typeOf function:

function typeOf(value) {
    if (value === null) return "null";
    if (value === void(0)) return "undefined";
    return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

You may read why I do so here.


Solution 3:

void is an operator that is used to return a undefined value so the browser will not be able to load a new page. An important thing to note about the void operator is that it requires a value and cannot be used by itself.

Example:-

 <a href="javascript: void(0)">I am a link</a>

Ouput:-

 I am a link

Solution 4:

the void(0) is used to return "undefined", you can write there just "undefined", and also dont use that javascript: in href attribute - because its so old and it will not work for users with javascript disabled, also if someone open this in a new window they will see something like javascript:showPopup(27);


Post a Comment for "What's A Good Use Of Void()"