JAVASCRIPT

JavaScript void Operator: Syntax, Usage, and Examples

The JavaScript void operator is an often overlooked but useful feature that evaluates an expression and returns undefined. Its primary use case is in scenarios where you want to execute some code but prevent any return value or default action from being processed, particularly in links, bookmarks, or self-executing expressions.

In web development, understanding this operator can help prevent unwanted page reloads and make your code behave consistently across browsers like Chrome and Firefox.

Developers working in frontend projects often encounter void when manipulating hyperlinks or controlling how actions execute within a web page.


What Is the JavaScript void Operator?

The JavaScript void operator is a unary operator that evaluates a given expression but always returns undefined regardless of the expression's actual result. It is written as void expression.

This operator ensures that no value is returned or processed after the expression is evaluated. The most common use of the void operator JavaScript pattern is in hyperlinks and bookmarklets, where returning a value (like a URL or function result) can interfere with expected behavior.

Since void affects how JavaScript functions behave, understanding it helps developers better manage event-driven actions inside the DOM (Document Object Model).

You can also explore detailed explanations and community discussions about the void operator on Github.


Basic Syntax

void expression;

Where expression can be any valid JavaScript code.

Example

void(0); // Returns undefined

This is the most common usage you’ll encounter, particularly in HTML links.

Sometimes developers add the void keyword before calling a JavaScript function in inline event attributes, ensuring the page doesn’t reload or trigger default behaviors when the function executes.


Understanding How the Void Operator Works

When JavaScript encounters void, it evaluates the expression inside parentheses but discards the result, always returning undefined.

let x = 10;
console.log(void(x + 1)); // undefined

Although x + 1 evaluates to 11, the void operator discards it and returns undefined.

This can be helpful when building small code snippets for testing or debugging UI behavior during frontend development.


Common Use: Preventing Link Navigation

A popular use of the JavaScript void operator is to prevent hyperlinks from navigating to another page or reloading the current page when clicked.

Without void (default behavior)

<a href="javascript:alert('Hello!')">Click me</a>

This works but is discouraged as it returns the result of alert(), and depending on the browser, it might cause navigation issues.

With void

<a href="javascript:void(0)">Click me</a>

This executes the code but doesn't navigate away from the current page.

You might also see this approach used with an anchor tag that performs a visual change or triggers a function without refreshing the web page.


void(0) vs void Expression

The most common expression used with void is 0, as it is a simple literal that evaluates immediately.

console.log(void(0)); // undefined
console.log(void "hello"); // undefined
console.log(void alert("Hi")); // Shows alert, then returns undefined

In all cases, the original result is discarded, and the value of the entire expression is undefined.

Developers working with TypeScript will also find that void plays a role in defining functions that explicitly return no value, improving clarity during type checking.


Using the Void Operator in Bookmarklets

A bookmarklet is a small JavaScript program stored as the URL of a bookmark. The void operator is frequently used to prevent unintended navigation when clicking on the bookmarklet.

Example

javascript:void(alert('You clicked a bookmarklet!'));

Without void, some browsers might interpret the result of alert() (which is undefined) as a new location to navigate to, leading to unexpected behavior like blank pages.


void with Immediately Invoked Function Expressions (IIFEs)

The void operator is sometimes used to define and immediately execute functions, especially before (()=>{})() became standard.

Example

void function() {
  console.log("Executed immediately");
}();

Although not commonly used today for IIFEs, this pattern was more relevant in earlier JavaScript development to ensure expressions were parsed correctly.

You can rewrite similar functionality today using an async function or modern constructor logic if your expression involves object creation or asynchronous code.


Alternative to Using void in HTML

In modern development, JavaScript event handling is preferred over embedding code in the href attribute.

Instead of:

<a href="javascript:void(0)" onclick="doSomething()">Click</a>

Use:

<a href="#" id="btn">Click</a>
<script>
  document.getElementById("btn").addEventListener("click", function(event) {
    event.preventDefault();
    doSomething();
  });
</script>

This separates behavior from structure and improves maintainability and accessibility.

Modern browsers like Chrome and Firefox handle event.preventDefault() more consistently than older inline approaches.

Additionally, developers can style these elements using CSS for visual feedback without relying on JavaScript in the markup.


Return Values and void

You can use the void operator when you want to run a function but ignore its return value explicitly.

function calculate() {
  return 42;
}

let result = void calculate(); // result is undefined

This can be helpful when you only care about side effects (e.g., logging, state changes), not return values.


void in Arrow Functions

The void operator can also be used in concise arrow functions where returning a value might not be necessary.

const logHello = () => void console.log("Hello");
logHello(); // Logs "Hello", returns undefined

This pattern is useful in functional programming where you want a clean side-effect-only function.


Comparing void to undefined

While void always returns undefined, they’re not interchangeable in all cases. undefined can be reassigned in old JavaScript environments, while void guarantees a true undefined result.

Example

let undefined = 10;
console.log(undefined); // 10

console.log(void 0); // undefined (always)

To avoid reassignment issues, especially in legacy code or polyfilled environments, void provides a safer method for producing undefined.


Edge Cases and Obscure Usage

  1. Multiple Statements Inside void

    void (console.log("One"), console.log("Two"));
    

    Only the final expression is returned (and discarded), but all expressions are evaluated.

  2. Using void in Expressions

    let result = 10 + void 0; // 10 + undefined → NaN
    

    This can result in tricky bugs and is discouraged unless explicitly needed.


When Should You Use the JavaScript Void Operator?

  • To prevent hyperlinks from performing default actions.
  • In bookmarklets to prevent navigation.
  • In concise arrow functions where return values are unnecessary.
  • As a safeguard to ensure a guaranteed undefined.

You might also use it when explaining how event-driven behavior differs across new page loads versus single-page applications.

In event-driven JavaScript functions, void can work alongside an event handler to ignore default link navigation entirely.

However, most use cases for void have been replaced by modern event handling practices and syntax improvements.


Best Practices for Using the Void Operator JavaScript Way

  1. Use Only Where Necessary: Most scenarios don’t require void. Use event.preventDefault() for preventing navigation.
  2. Avoid Inline JavaScript in HTML: Keep JavaScript in <script> tags or external files instead of using href="javascript:void(0)".
  3. Use Readable Alternatives: Instead of writing void someFunction(), consider refactoring your code to make return values irrelevant.
  4. Don’t Use void for Style or Obfuscation: Some developers use void to shorten or obscure code, which can hurt readability.

The JavaScript void operator is a specialized feature that evaluates an expression and discards its result, always returning undefined. While its use has declined with the rise of cleaner and more modern patterns like event.preventDefault() and arrow functions, understanding the void operator JavaScript style remains useful, especially when dealing with legacy code, bookmarklets, or concise side-effect functions.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster