For example, the following expression between
2 + 2 will return
let num = 2 + 2; console.log(num); // 4
When you evaluate the expression using the
void keyword, the expression will return
undefined instead of the actual result:
let num = void (2 + 2); console.log(num); // undefined
Even though the
num keyword is
let num = void console.log(2 + 2); // 4 console.log(num); // undefined
In short, the code that follows the
As a web developer, you may sometimes find
href attribute for some
For example, you might find a button to print the web page written as follows:
href attribute like
tel: for phone numbers and
sms: to launch the SMS application of your phone.
0 inside the
void operator is simply used as a placeholder. By using
<a> tag won’t send you to other web address. It also won’t refresh the page as links usually do when you put
/ as the value of
You may wonder then why not just remove the
href attribute? Well, removing the
href attribute will cause the pointing finger mouse icon to turn into a caret for text.
In short, putting
href attribute will create a link that does nothing.
The example link above will run the
printPage() function when clicked without refreshing the page or sending you anywhere.
When do you need to use void?
For example, you can re-assign the
undefined keyword as another value:
undefined = 9; console.log(9 === undefined); // false
The example above will return
true before the ES5 update in 2009, so you want to check for undefined with
void 0 instead:
console.log(void 0); // undefined console.log(9 === void 0); // false
undefined is read-only after ES5, so you don’t need
void 0 anymore.
As for preventing the default behavior of
<a> tag, it’s generally encouraged for you to use
<button> for buttons and
<a> for links.
When you need to change the cursor, it’s recommended to use CSS instead of using the