DEV Community

Sourav Bandyopadhyay
Sourav Bandyopadhyay

Posted on

2

JavaScript : Void Operator

Are you familiar with the void operator in JavaScript? It's a little-known but powerful feature that can come in handy when working with certain types of data.

In JavaScript, void is a unary operator that takes an expression as its operand and evaluates it to be undefined. Although doing this can seem unusual, there are several situations in which it might be advantageous.

Making a link that doesn't actually go somewhere is one of the most frequent uses of void. You might, for instance, want to design a button that, when clicked, executes some action, but you don't want the visitor to be directed to a different website. An empty link known as a "dummy" link can be made by setting the href attribute of an anchor element to javascript:void(0).

Forcing the browser not to follow a link after it has been clicked is another application for void. You may stop the default action of a link by adding an event listener to it and using event.preventDefault() in the listener (i.e. navigating to a new page). But, some older browsers don't support preventDefault(), thus using void can be a more certain way to get the same effect.

Overall, void might not be the most commonly used feature in JavaScript, but it can definitely come in handy in certain situations. Have you ever used void in your own code? Let me know in the comments! 💭

<button onclick="myFunction()">Click me</button>

<a href="javascript:void(0)" onclick="myFunction()">Click me instead</a>
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay