Shortcuts
Introduction
- Operator reference (developer.mozilla.org)
Examples
n = +'4096' // n === 4096
s = '' + 200 // s === '200'
now = +new Date()
isPublished = !!post.publishedAt
See: Unary plus (developer.mozilla.org)
Comparison
| What | Lazy mode | "The right way" |
|---|---|---|
| String to number | +str | parseInt(str, 10) or parseFloat() |
| Math floor | num | 0 | Math.floor(num) |
| Number to string | '' + num | num.toString() |
| Date to UNIX timestamp | +new Date() | new Date().getTime() |
| Any to boolean | !!value | Boolean(value) |
| Check array contents | if (~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!