12 JS Tricks
Source: https://medium.com/@bretcameron/12-javascript-tricks-you-wont-find-in-most-tutorials-a9c9331f169d
Filter Unique Values
The Set
object type was introduced in ES6, and along with ...
, the ‘spread’ operator, we can use it to create a new array with only the unique values.
Before ES6, isolating unique values would involve a lot more code than that!
Cache Array Length in Loops
Standard structure:
This syntax, the for
loop re-calculates the length of the array with every iteration.
In most cases, it is better and more performant to cache the array’s length so that it only needs to be calculated once:
As an array increases in size, no run-time is lost to re-calculating array.length
.
Short-Circuit Evaluation
Convert to boolean
Besides the regular boolean values true
and false
, JS also treats all other values as either ‘truthy’ or ‘falsy’.
All values in JavaScript are ‘truthy’ with the exception of 0
, ""
, null
, undefined
, NaN
and of course false
We can easily switch between true and false by using the negative operator !
, which will also convert the type to "boolean"
:
This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define false
as !1
is if you were playing code golf!
Convert a number to String
Use the concatenation operator +
followed by ""
.
Convert a string to number
Using the addition operator +
.
May also be used to convert booleans to numbers, as below:
There may be contexts where the +
will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes: ~~
.
A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to-n — 1
. So, for example, ~15
is equal to -16
.
Using two tildes in a row effectively negates the operation, because — ( — n — 1) — 1 = n + 1 — 1 = n
. In other words, ~ — 16
equals 15
.
Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans: ~true = -2
and ~false = -1
Automatic Binding in Classes
By using arrow notation in class methods binding is implied.
Avoiding repetitive expressions like this.myMethod = this.myMethod.bind(this)
Get the Last Item(s) in an Array
The array method slice()
can take negative integers, and if provided it will take values from the end of the array rather than the beginning.
Last updated