📜  void 0 js - Javascript (1)

📅  最后修改于: 2023-12-03 14:48:21.439000             🧑  作者: Mango

void 0 in JavaScript

Introduction

As a JavaScript programmer, you may have come across the unusual syntax void 0. This syntax is used in some JavaScript code, but what does it actually do? This article will explore what void 0 is, how it works, and some examples of its usage.

What is void 0?

void 0 is a built-in JavaScript function that returns the value undefined. The void operator evaluates an expression and then returns undefined. The 0 in void 0 is used as a placeholder expression. Any other number or expression could be used in its place, but 0 is commonly used as it is a literal that evaluates to 0.

How does void 0 work?

The void operator takes an expression as its operand and evaluates it. It then returns undefined. If the expression is omitted or yields no value, the operator will instead return undefined. Since 0 is a falsy value in JavaScript, void 0 will always return undefined and cannot be accidentally overwritten.

console.log(void 0); // Output: undefined
Examples of void 0 usage
Preventing navigation

One common use of void 0 is to prevent navigation when clicking on a hyperlink. The href attribute of a hyperlink is used to specify the destination URL. However, if the hyperlink is clicked without a valid URL, the browser will navigate to the current URL, which is typically not the intended behavior.

<a href="javascript:void 0;"
   onclick="alert('Clicked!')">Click Me</a>

In this example, the hyperlink's href attribute is set to void 0, which evaluates to undefined. When the hyperlink is clicked, nothing will happen because the onclick event will only trigger an alert message. This prevents any unexpected navigation from occurring.

Bookmarklet

Another use of void 0 is to create bookmarklets. A bookmarklet is a small script that is stored as a bookmark in a web browser. When the bookmark is clicked, the script is executed on the current web page.

javascript:void(window.alert('Hello World!'));

In this example, the void operator is used to prevent the browser from navigating to a new page when the bookmarklet is clicked. Instead, the script within the bookmarklet will be executed on the current page.

Conclusion

In summary, void 0 is a built-in JavaScript function that returns the value undefined. It is commonly used to prevent navigation when clicking on a hyperlink and to create bookmarklets. The void operator takes an expression as its operand and evaluates it, returning undefined. Since 0 is a literal that evaluates to 0, void 0 will always return undefined and cannot be accidentally overwritten.