What is Javascript void(0): Learn Javascript void(0) in details

What is Javascript void(0)?

What is Javascript void(0)

Javascript void(0): Using JavaScript void operator evaluates the given expression and then returns a value of undefined.

We often use void operator when we inserting an expression in a web page might produce some unwanted effect.

To remove this unwanted effect we can use “javascript:void(0)”. This “javascript:void(0)” expression returns undefined primitive value.

With hyperlinks, we are commonly using JavaScript:void(0) operator.

Sometimes, we decide to call some JavaScript from inside a link. In general, when we click a link then the browser loads a brand new page or refreshes the same page.

But sometimes we don’t want this to happen when we attached some JavaScript to that link.

To prevent this default behavior, I mean, we can prevent the page from refreshing, we could use “javascript:void(0)”.

 

Example of Using “#” in anchor tag:

Now let’s have look at what would happen if we didn’t use JavaScript:void(0); within the anchor link.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Without JavaScript:void(0)</title>
</head>
<body>
        <h1>Without JavaScript:void(0)</h1>
	<a href="#" ondblclick="alert('Now, you are ready to go!')">Double Click Me!</a>
</body>
</html>

Output:

 without JavaScript:void(0)

 without JavaScript:void(0)

 

When we clicked the link then the page will be refresh. Even if we double-clicked and triggered the ondbclick event, it will still happen.

The void operator can be useful for us when we need to call another function that may have otherwise resulted in an unwanted page refresh.

Using “javascript:void(0);” in anchor tag:

We have a link that should only do something when we double click on the link. Nothing will happen if we click once. Actually, we can specify the double click code by using the ondblclick event handler. Using this “javascript:void(0);” operator in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Example of JavaScript:void(0)</title>
</head>
<body>
        <h1>Example of JavaScript:void(0)</h1>
	<a href="javascript:void(0);" ondblclick="alert('Now, you are ready to go!')">Double Click Me!</a>
</body>
</html>

 

Output:

 

javascript:void(0)

javascript:void(0)

 

Close