15

I came across this snippet in kriskowal/q:

/**
 * Applies the promised function in a future turn.
 * @param object    promise or immediate reference for target function
 * @param args      array of application arguments
 */
Q.fapply = fapply;
function fapply(value, args) {
    return dispatch(value, "apply", [void 0, args]);
}

What is the point of using the void keyword? Why not just write [undefined, args]?

Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • 9
    Because global `undefined` can be redefined; it's not a reserved word, like `null`. – raina77ow Mar 05 '13 at 18:42
  • 2
    ..can be redefined, but starting in JavaScript 1.8.5, undefined is non-writable, as per the ECMAScript 5 specification. – epascarello Mar 05 '13 at 18:45
  • 6
    `void 0` is 3 less characters than `undefined`. – gen_Eric Mar 05 '13 at 19:11
  • Also useful as a hack to remove/reapply a CSS class: https://css-tricks.com/restart-css-animation/ – Sphinxxx Aug 31 '17 at 19:43
  • 1
    Can also be used in place of paranthesis to define an anonymous function as an expression (e.g., for IIFEs, `void function() { console.log("Look ma, no external paranthesis!"); }()`) – Nick Bull Mar 20 '18 at 10:14

2 Answers2

15

From the MDN Docs of void

Syntax

void expression

Uses

This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.

The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

And why? See MDN Undefined

In older versions of JavaScript undefined could be overridden, but in starting in JavaScript 1.8.5, undefined is non-writable, as per the ECMAScript 5 specification.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • 4
    Ok, so it's just a safer way of writing `undefined`? – Nick Heiner Mar 05 '13 at 18:51
  • 1
    yes, that is the reason. – epascarello Mar 05 '13 at 18:52
  • 1
    @Rosarch: To be clear, the global `undefined` is non-writeable. You can still shadow it in a local variable scope. But make sure you don't allow any code to redefine `undefined`, and it's plenty safe to use. – the system Mar 05 '13 at 18:59
  • ✅ you can void anything, it always returns undefined! ```js void 0 === void(0); // true void 0 === void(true); // true void false === void(true); // true ``` ```js void 0 === void(0); // true void 0 === void(true); // true void false === void(true); // true ``` – xgqfrms Sep 27 '20 at 04:54
1

The void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type.

This operator specifies an expression to be evaluated without returning a value. Its syntax could be one of the following