What does void 0 mean?

Sometimes I see such links

<a href="javascript:void(0)">Войти</a>

And void 0 is also used in the Backbone library.js, for example:

if (obj == null) return void 0;

What does void 0 mean, and what is it for?

Author: Peter Olson, 2015-07-07

1 answers

Operator void[MDN][specification] evaluates the passed expression and always returns undefined.

Examples:

void 0          // возвращает undefined
void(0)         // это тоже возвращает undefined
void "привет"   // тоже возвращает undefined
void new Date() // всегда возвращает undefined

Why do I need this operator at all?

If void 0 always returns undefined, you can just use undefined, right?

Can. Actually, void is not a very useful operator, and I use it very rarely. But it is useful in some situations:

  • In older browsers (I'm not sure which ones. In my opinion, in IE 6 and below and in Netscape) it was possible to change the value of undefined:

    undefined = 5;   // в старых браузерах изменит значение undefined,
                     // в новых ничего не делает
    5 === undefined; // true в старых браузерах, false в новых
    

    It is not always known what undefined means undefined. Therefore, some libraries use void 0.

  • Even in new browsers, undefined is a valid variable name inside a function:

    function f() {
      var undefined = 5;
      return undefined;
    }
    f(); // возвращает 5
    

    But if you write such code, it's your fault.

  • If you want to save your energy: void 0 is three characters shorter than undefined. Although 0[0] even shorter.

A link starting with javascript: usually sends the user to a page with the text that the code returns. For example:

Нажимай <a href="javascript: 'Привет!'">СЮДА</a>!

But if you want the link to not send the user anywhere, you need to return undefined somehow. Traditionally, people use void(0), but undefined and other options also work.

<a href="javascript:void(0)">Войти</a>

Why void 0?

This is just a tradition; void 0 - simple and short code. Other options, such as void 9 and void "привет", also work.

 26
Author: Peter Olson, 2015-07-07 07:08:08