Javascript link Void 0

Recently, I’ve seen several instances of “javascript:void(0)” in existing code. For example:

It confused me enough that I thought I’d aggregate a few StackOverflow posts.

1) void(0) returns undefined.

The void operator evaluates the given expression and then returns undefined.

It can also be written “void 0”, which does the exact same thing.

 

2) The Browser will navigate javascript links that return a value by default.

If you have a snippet like the following

And iReturnOne() returns the string “one”. The browser’s default behavior will be to navigate to a new, blank page, which contains nothing but the output “one”.

Try it here: https://jsfiddle.net/p418pght/

The exception is when the function returns undefined.

 

3) Navigation does not occur when the function returns undefined.

If you change your function to return undefined, the page will no longer navigate.

 

4) So use “void(0)” to prevent navigation.

Changing the above to

We now have an example that will not navigate.

Try it here: https://jsfiddle.net/jzz326gu/1/

 

5) This is not the best way to do things.

If you’re looking at existing code, then fine, but if you’re writing new code, you probably should not do this.

If you want your link to do something when it gets clicked, it’s cleaner to listen to the onclick event than it is to include inline javascript in your HTML.

Why?

  1. Separation of JavaScript and HTML is better because it keeps all of your scripts in one place. If someone is reading your code trying to figure out what it does, they might miss the little snippet of JavaScript you have hiding in your HTML, even if they understand the rest.
  2. “void 0” is goofy syntax that very few, even senior JavaScript developers understand. Better not to use esoteric language features for brownie points. They will just confuse future developers.