JS Operators

Posted on 2021-04-28

Some less used JS operators

Tilde Operator (~) - Bitwise Not operator
if (str.indexOf("abc")!==-1) {
  //....
}

//BECOMES
if (~str.indexOf("abc")) {
  //....
}

Double Tilde Operator (~~)

Converting strings to numbers using the tilde twice for positive numbers

console.log(~~"9") //9

Double Bang Operator (!!)

Convert a value into boolean

!!"abc" // Evaluates to true.
!!null // Evaluates to false.
!!"" // Evaluates to false.

//empty array/ object has a truthy value.
//empty string has a falsy value.

Truthy:
object, array, string, numbers other than 0, date (e.g. new Date())


Falsy:
Empty string (""), 0, null, undefined, NaN

JavaScript
© 2021 Betty Leung