DEV Community

Discussion on: Top 5 JavaScript secrets

Collapse
 
koire profile image
Koire

I think this post should have a disclaimer at the top: "Please don't use this in production code"

On the other hand, void is useful when you are writing one-liners for hooks in React, because React will throw an error if you don't return a function or null:
useEffect(() => void setTimeout(myfunction, sometime))

Collapse
 
jsmanifest profile image
jsmanifest • Edited

void is also useful if you write switch statements like this:

switch (dataKey) {
  case 'hello':
    api.sortMyStuff()
    break
  case 'how are you':
    api.sortSomeoneElsesStuff()
    break
  default:
    break
}

You can reduce a couple of lines using them this way while maintaining the exact behavior:

switch (dataKey) {
  case 'hello':
    return void api.sortMyStuff()
  case 'how are you':
    return void api.sortSomeoneElsesStuff()
  default:
    return void
}