Why does the JavaScript void statement evaluate an expression?

The JavaScript void operator evaluates an expression and always returns undefined, regardless of what the expression returns. This is useful for preventing unwanted side effects in web pages.

What is the void Operator?

The void operator takes any expression, evaluates it, and returns undefined. It's commonly used in links to prevent navigation while still executing JavaScript code.

Syntax

void expression
void(expression)

Example: Using void(0) in Links

The most common use case is void(0) in hyperlinks to prevent page navigation:

<!DOCTYPE html>
<html>
<head>
    <title>Understanding JavaScript void(0)</title>
</head>
<body>
    <a href="javascript:void(0);" ondblclick="alert('Click it twice!')">Click me not once, but twice.</a>
</body>
</html>

In this example, javascript:void(0) prevents the page from reloading when clicked once. The alert only appears on double-click due to the ondblclick event handler.

How void Works with Different Expressions

console.log(void 0);           // undefined
console.log(void 1);           // undefined
console.log(void true);        // undefined
console.log(void "hello");     // undefined
console.log(void (2 + 3));     // undefined
undefined
undefined
undefined
undefined
undefined

Practical Use Cases

1. Preventing Link Navigation:

<a href="javascript:void(0);" onclick="doSomething()">Action Link</a>

2. Getting Pure undefined:

let result = void 0;  // Guaranteed undefined
console.log(result);  // undefined
console.log(typeof result);  // "undefined"
undefined
undefined

Alternative Approaches

Method Purpose Example
void(0) Get undefined, prevent navigation href="javascript:void(0)"
return false Prevent default behavior onclick="doAction(); return false;"
preventDefault() Modern event handling event.preventDefault()

Conclusion

The void operator evaluates expressions and returns undefined, making it useful for preventing unwanted link navigation. Modern alternatives like preventDefault() are often preferred for event handling.

Updated on: 2026-03-15T23:18:59+05:30

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements