cheatsheets/js-lazy.md

34 lines
795 B
Markdown
Raw Permalink Normal View History

2017-03-07 08:03:11 +00:00
---
title: JavaScript lazy shortcuts
category: JavaScript
---
2017-08-28 17:39:39 +00:00
## Shortcuts
{: .-left-reference}
### Examples
```js
n = +'4096' // n === 4096
s = '' + 200 // s === '200'
```
```js
now = +new Date()
isPublished = !!post.publishedAt
```
### Shortcuts
2017-03-07 08:03:11 +00:00
| What | Lazy mode | "The right way" |
| --- | --- | --- |
2017-08-28 17:39:39 +00:00
| String to number | `+str` | `parseInt(str, 10)` _or_ `parseFloat()` |
2017-03-07 08:03:11 +00:00
| 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)` |
2017-03-07 08:51:40 +00:00
| Check array contents | `if (~arr.indexOf(v))` | `if (arr.includes(v))` |
2017-08-28 17:39:39 +00:00
{: .-left-align.-headers}
2017-03-07 08:03:11 +00:00
2017-08-28 17:39:39 +00:00
`.includes` is ES6-only, otherwise use `.indexOf(val) !== -1` if you don't polyfill.