What does “javascript:void(0)” mean?


In this tutorial, we will learn what “javascript: void(0)” means.

In English, void means nothing. In a programming language, void means return nothing. “javascript: void(0)” is similar to void.

javascript: void(0) means return undefined as a primitive value. We use this to prevent any negative effects on a webpage when we insert some expression.

For example, in the case of URL hyperlinks. Hyperlinks open by reloading the page when the user clicks on the link. When you need to run some other code in such cases, you can use javascript: void(0).

Let’s split javascript: void(0) with a colon. We get javascript and void(0).

javascript: is a pseudo URL. The JavaScript engine interprets this as some code after that colon and executes that code.

Syntax

<a href="javascript:console.log('1');">Link</a>

Here, displays 1 in the console when we click the link.

const result = void(1 + 1);
console.log(result);//undefined
console.log(void(0) === undefined)//true

void(0) returns undefined. void(0) means void(false). Even if 1+1 is 2, void makes it undefined.

<a id='href' href="javascript: void(document.querySelector('#href').style.color='purple')">Click Me</a>

In the above snippet, the code inside the void executes.

Without using javascript: void(0)

Example

In this example, we have set # to the href and added a double-click event to the anchor tag. Only when the user doubles clicks on the tag, does the alert trigger. Here the page refreshes because we have set #. We can also observe the color change of the link.

<html> <body> <h2>JavaScript program without using <i>javascript: void(0)</i></h2> <a href="#" ondblclick="alert('Clicked Twice')">Double Click Me!</a> </body> </html>

Use javascript: void(0)

Example

In this example, we have set javascript: void(0) to the href and added a double-click event to the anchor tag. Only when the user doubles clicks on the tag, does the alert trigger. Here page does not refresh because we have set javascript: void(0). We can not observe the color change of the link because we didn’t visit it.

<html> <body> <h2>JavaScript program using javascript: void(0)</h2> <a href="javascript: void(0)" ondblclick="alert('Clicked Twice')">Double Click Me!</a> </body> </html>

In this tutorial, we have discussed the javascript: void(0). We can use this option when we need to prevent some action on a webpage.

Updated on: 31-Oct-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements