Skip to main content

JavaScript tips

JavaScript tips

Shorthand

Boolean(0)!!0
String(3.14)3.14 + ""
Number("3.14")+ "3.14"
Math.floor(3.14)~~3.14 or
3.14 << 0
undefinedvoid 0
100001e4

flatMap

result = []
for (v of array)
if (v !== 0)
array.push(1/v)
  • array.map(v => v !== 0 && 1/v).filter(v => v)
  • array.flatMap(v => v === 0? []: 1/v)

Math

const {sin, asin} = Math
[0, 1, 2].map(sin).map(asin)

template literal

function upper(args) {
return args[0].toUpperCase()
}
const text = upper`hi` // HI

functional object

const hello = () => 'HELLO'
hello.world = () => 'WORLD'
hello() // HELLO
hello.world() // WORLD

assignment

let t = -1,
dt = 100 - (~t? t: (t = 0))
console.log(t) // 0