Javascript idioms
From Zoltan Kochan, author of pnpm
Double exclamation
Prefixing anything with
!!
converts it to a boolean.var foo = 0 console.log(!!foo) //> false
Essentially it is a shorter way to write
Boolean(foo)
.Converting arguments to array
The arguments object can be used to access the arguments passed to the function. However, it is not an Array so it doesn’t have Array properties except
length
. TheArray.prototype.slice.call(arguments)
idiom is used very frequently to convert the argument’s object to an actual array.(function() { console.log(arguments instanceof Array) //> false var args = Array.prototype.slice.call(arguments) console.log(args instanceof Array) //> true })()
Assigning default values
function foo(opts) { var msg = opts.message || 'Hello world!' console.log(msg) } // instead of function foo(opts) { var msg = opts.message ? opts.message : 'Hello world!' console.log(msg) }
More examples of interesting
||
and&&
usages can be found in the 12 Simple (Yet Powerful) JavaScript Tips article.Converting to array if not already
var totallyArray = [].concat(value) //instead of var totallyArray = value instanceof Array ? value : [value]
Converting strings to number
var foo = +'12.2' var bar = +'12' // instead of var foo = parseFloat('12.2') var bar = parseInt('12')
Checking if an array includes an element
if (~[1, 2, 3].indexOf(2)) { console.log('includes') } // instead of if ([1, 2, 3].indexOf(2) > -1) { console.log('includes') }
There are some other usage examples for the tilde operator as well in The Great Mystery of the Tilde(~).
Writing multi-line strings
var multiStr = [ "This is the first line", "This is the second line", "This is more..." ].join("\n"); // instead of var multiStr = "This is the first line\n" + "This is the second line\n" + "This is more...";
Looping through an array
It can be used if order is not important
for (var i = arr.length; i--;) { // ... } // instead of for (var i = 0; i < arr.length; i++) { // ... }
setTimeout(func, 0)
JavaScript code runs on one thread. Calling
setTimeout
with0
allows to schedule a function to run after the current event loop tick.setTimeout(function() { console.log('log message from next tick') }, 0) console.log('Hello world!') //> Hello world! //> log message from next tick