Dan D Kim

Let's share stories

Double Tilde ~~ and Double Apostrophe !! - SUPER USEFUL to know

2020-04-20 Dan D. Kimjavascript

Are you planning on doing your technical interview in Javascript?

If so, here are some useful notations that may save you from writing too much boilerplate code! Keeping your code short and concise will win you bonus points in an interview, because you spend less time on writing the code and more time on the actual interview.

Double Tilde ~~

Consider the following.

const dict = new Map()

function incrementCount (letter) {
  if (dict.has(letter)) {
    dict.set(letter, dict.get(letter) + 1)
  } else {
    dict.set(letter, 1)
  }
}

With double tilda, this reduces to the following.

const dict = new Map()

function incrementCount (letter) {
  dict.set(letter, ~~dict.get(letter) + 1)
}

Why?

dict.get(letter) will return undefined when letter doesn’t exist.

~~undefined will return 0.

Double Apostrophe !!

Consider the following.

const customerCanPay = hasMoney && customer !== undefined

With double apostrophe, this gets slightly reduced.

const customerCanPay = hasMoney && !!customer

Why?

! evaluates the proceeding value to a truthy value. In our case, it returns false because the value is defined.

!! will simply flip the false to true.

But you might ask: “Can’t you just do this:”

const customerCanPay = hasMoney && customer

In this case, customerCanPay will not be a truthy value, but instead it will be assigned to the customer object.

Coming from the MDN docs:

// If expr1 can be converted to true, returns expr2; else, returns expr1.
expr1 && expr2

If hasMoney evaluates to true, the next expression will be returned as a whole, instead of converting it to a truthy value.


That’s all! Hope you learned something. Happy interviewing :)