The void operator in JavaScript is one of those rare features that most developers don’t use often — but it has a few interesting use cases. It simply evaluates an expression and returns undefined.
Syntax
void expression
It doesn’t change or run the expression in a special way — it just ignores the result and returns undefined.
Basic Example
console.log(void 0); // undefined
console.log(void (2 + 2)); // undefined
Even if the expression returns something, void ensures the final result is always undefined.
Why Use void?
It may seem useless at first, but here are a few cases where it’s handy:
1. Prevent Navigation in <a> Tags
<a href="javascript:void(0)">Click Me</a>
This stops the page from reloading or navigating anywhere when the link is clicked. It’s better than using # because it avoids messing with the page’s scroll position or URL fragment.
2. Bookmarklets
Bookmarklets are small pieces of JavaScript you can save as bookmarks. To make sure they don’t accidentally redirect the page, developers often wrap them in void:
javascript:void(alert('Hello from a bookmarklet'));
3. Forcing undefined in Older Browsers
In older versions of JavaScript (ES3), undefined could be reassigned. So people used void 0 to safely get a guaranteed undefined value:
var undef = void 0;
Nowadays, undefined is a reserved word, so this trick isn’t needed — but you might still see it in legacy code.
Is void Still Useful Today?
Mostly in two cases:
- Preventing navigation in HTML links
- Creating or maintaining bookmarklets
In general coding, we rarely use void, but it helps to know what it does when you see it.
Conclusion
The void operator isn’t something you’ll use daily, but it’s good to understand it — especially if you work with bookmarklets, legacy code, or want to safely avoid link navigation. It simply forces an expression to return undefined, no matter what the expression actually does.
Now when you see void(0), you’ll know exactly what’s going on behind the scenes!
Post a Comment