DEV Community

Discussion on: VOID in JavaScript

Collapse
 
lionelrowe profile image
lionel-rowe

You mention that void is an operator, just like + is, but it seems there might be some confusion between operators and functions. void doesn't need to be "called" with parentheses, and the expression that follows it isn't an "argument".

  • void 0 and void(0) are the same, just as +0 and +(0) are the same.
  • void; is a syntax error, as is +;, whereas someFunction; isn't.

One other handy usage for the void operator is with simple arrow functions in TypeScript where undefined is the expected return type and you want to do something side-effect-ey that returns a value:

type PushFn = (n: number) => undefined

const arr: number[] = []

// Type error: Type 'number' is not assignable to type 'undefined'.
const pushFn1: PushFn = (n) => arr.push(n)

// OK
const pushFn2: PushFn = (n) => void arr.push(n)
Enter fullscreen mode Exit fullscreen mode