Shorthand idioms for coercing values in JavaScript, and the explicit calls they replace.

Shortcuts

Introduction

Examples

n = +'4096'    // n === 4096
s = '' + 200   // s === '200'
now = +new Date()
isPublished = !!post.publishedAt

See: Unary plus (developer.mozilla.org)

Comparison

WhatLazy mode"The right way"
String to number+strparseInt(str, 10) or parseFloat()
Math floornum | 0Math.floor(num)
Number to string'' + numnum.toString()
Date to UNIX timestamp+new Date()new Date().getTime()
Any to boolean!!valueBoolean(value)
Check array contentsif (~arr.indexOf(v))if (arr.includes(v))

.includes is ES2016-only, otherwise use .indexOf(val) !== -1 if you don't polyfill. num | 0 rounds toward zero and wraps at 32 bits, unlike Math.floor().

See: parseInt(), Math.floor(), Boolean() (developer.mozilla.org)

0 Comments for this cheatsheet. Write yours!