DEV Community

Discussion on: Improve your JS skills with those tips #1

Collapse
 
whaison profile image
Whaison • Edited

Nice Article

Btw, you don't have to use the double not (!!) operator in a condition. It is enough to just write

if (value) { 
  ...
}
Enter fullscreen mode Exit fullscreen mode

because an if statement checks the truthyness (or the falsyness) of the value.

falsy values are:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

Everything else will be treated as truthy.
The same rules apply to Boolean(value) and !!value.

This also works inside other boolean expressions so you can write for example:

let item = response.body && response.body.item || 'default'
Enter fullscreen mode Exit fullscreen mode

-> If the body of the response is truthy and the item field is truthy: assign item = response.body.item. If either of them is falsy assign item = 'default'.

NOTE: in JavaScript the && and || operators work differently than in other languages

left && right === left  // if left is falsy
left && right === right // if left is truthy

left || right === right // if left is falsy
left || right === left  // if left is truthy
Enter fullscreen mode Exit fullscreen mode
Collapse
 
codeoz profile image
Code Oz

Nice to know this! Thank you for sharing this it's very interesting Whaison