Connect with us

Programming

Void 0 in JavaScript: Meaning, examples, and when to use it

Understand JavaScript’s void 0, why it returns undefined, how side effects work, and why javascript:void(0) is usually a poor link choice.

Published

on

JavaScript void 0 example with undefined shown in a console

In JavaScript, void 0 evaluates the number 0 and returns undefined. The void operator discards the value of its operand after evaluating it. You may encounter this expression in compressed code, older libraries, and links written as javascript:void(0).

For ordinary application code, writing undefined is usually easier to read. Understanding void is still useful because it explains why an expression can return nothing useful while the operation inside it still happens.

What the expression does

console.log(void 0);       // undefined
console.log(void (0));     // undefined
console.log(typeof void 0); // "undefined"

The parentheses in the second example group the operand. They do not turn void into a function. The operator takes an expression, evaluates it, and produces the primitive value undefined. The number zero has no special power here; it is simply a short, harmless operand.

MDN’s void reference documents the syntax and its common uses. When reading code, identify the entire operand before deciding what the statement does. An operator that discards a result can still evaluate a complicated expression.

Void does not stop side effects

Here is a small example you can run in a JavaScript console. The array changes even though the assigned result is undefined:

const events = [];
const result = void events.push("saved");

console.log(events); // ["saved"]
console.log(result); // undefined

push adds the item and ordinarily returns the new array length. Applying void discards that returned length. It does not undo the insertion. This distinction matters when the operand sends a request, changes an object, or invokes another function.

For a debugging check, replace the operand with a function that records when it runs. If the record changes, the operation took place regardless of the value returned by the surrounding expression. This is more informative than examining only the final console result.

The array changes even though void discards the return value of push.
The array changes even though void discards the return value of push.

Why developers sometimes use it instead of undefined

In modern JavaScript, the global undefined property cannot be reassigned in the ordinary way. However, a function parameter can use the same name and hide that global identifier within its scope. The following deliberately awkward example demonstrates the difference:

function demonstrate(undefined) {
  return [undefined, void 0];
}

console.log(demonstrate("local value"));
// ["local value", undefined]

The first array element reads the parameter. The second evaluates void 0, which does not depend on that parameter’s value. This explains one reason the shorter expression appears in generated or defensive code.

For code you maintain, avoid naming a parameter undefined. Clear names remove the confusion at its source. There is little benefit in making every assignment harder to read merely because shadowing is possible in a contrived example.

Check precedence when the operand gets longer

Parentheses help make the intended operand obvious. Compare these two original examples:

console.log(void 2 === undefined);   // true
console.log(void (2 === undefined)); // undefined

In the first expression, the result of void 2 is compared with undefined. In the second, the comparison is inside the parentheses, so its Boolean result is discarded by void. The expressions contain almost the same characters but answer different questions.

If an expression needs a long explanation about precedence, consider splitting it into named steps. That makes it easier to inspect intermediate values and reduces the chance that a future edit changes what is being discarded.

Using void in a callback

An expression-bodied arrow function returns its expression’s result. Sometimes you want the callback to perform an operation without returning that operation’s value:

const queue = [];
const add = item => void queue.push(item);

console.log(add("first")); // undefined
console.log(queue);        // ["first"]

The block-bodied version is often clearer:

const addClearly = item => {
  queue.push(item);
};

Both versions add an item without returning the array length. Choose the one that makes the callback’s purpose easiest for your team to understand. Do not assume every event system interprets callback return values in the same way; use that API’s documented cancellation or control mechanism.

An action uses a button with separately attached JavaScript behavior.
An action uses a button with separately attached JavaScript behavior.

What javascript:void(0) does in a link

A javascript: URL asks the browser to evaluate code when the URL is used for navigation. MDN’s javascript URL documentation explains that a string completion value can replace the current document. Returning undefined avoids that particular replacement behavior.

That explains the old pattern href="javascript:void(0)": the expression produces no string document to display. It does not give the element a meaningful destination, make a broken click handler work, or establish that the action is accessible.

If the control performs an action, use a button. If it navigates to another page, use a link with a real destination. A button can have its behavior attached separately:

<button type="button" id="open-settings">Open settings</button>
const control = document.querySelector("#open-settings");
control.addEventListener("click", openSettings);

This example assumes openSettings is a function your application defines. An actual settings dialog also needs appropriate focus handling and a way to close it. Our web development articles cover related interface work.

Void does not handle errors or promises

If the operand throws an error, adding void does not catch it. The evaluation stops with that error. Use a suitable error-handling path for the operation itself.

try {
  void (() => { throw new Error("example"); })();
} catch (error) {
  console.log(error.message); // "example"
}

Likewise, void doAsyncWork() is not the same as awaiting the promise. It does not wait for completion or install a rejection handler. Discarding the returned promise can leave a failure unhandled if the operation has no other error-handling path.

When work must finish before the next step, use the appropriate asynchronous control flow. When intentionally starting background work, make its failure handling explicit. The absence of a returned value says nothing about whether the operation succeeded.

Debug the exact expression you found

If a page shows a javascript:void(0) link that does nothing, inspect the expected click behavior, script loading, and console errors. Changing the text to a different no-op expression is unlikely to restore a missing event handler.

When reading compressed JavaScript, use formatting tools to separate statements before editing. Locate the function call inside the operand and follow its side effects. Keep any change in readable source where possible, then rebuild through the project’s normal process.

More language explanations are available in our Programming section. A small console example with a known output is often the quickest way to settle what a short operator expression actually returns.

Keep undefined separate from null

The result of void 0 is not null. If your application uses null to mean that a user deliberately cleared a field, replacing it with undefined may change how the surrounding code handles the field. Check the actual data contract before making that substitution.

A useful review question is whether the code intends to produce an undefined value or merely ignore the result of an operation. The first concerns the value being passed to another part of the program. The second concerns what the operation does and how its errors are handled.

Frequently asked questions

Does void 0 return zero?

No. The operand is zero, but the result of the void expression is undefined.

Are void 0 and void(0) different?

No. The parentheses group the same operand. Void is an operator in both forms.

Does void cancel a function call?

No. The function is evaluated. Its returned value is discarded, while side effects and thrown errors still matter.

Should I use javascript:void(0) for a button?

Use a real button for an action and attach its behavior appropriately. A JavaScript URL does not provide a useful navigation destination.

Does void handle a rejected promise?

No. It does not add a catch handler or wait for the promise. Handle asynchronous errors explicitly.

Shabbir Ahmad is a highly accomplished and renowned professional blogger, writer, and SEO expert who has made a name for himself in the digital marketing industry. He has been offering clients from all over the world exceptional services as the founder of Dive in SEO for more than five years.

Read About

shifted magazine sidebar

Trending Posts