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.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

Before ES6, isolating unique values would involve a lot more code than that!

Cache Array Length in Loops

Standard structure:

for (let i = 0; i < array.length; i++){
  console.log(i);
}

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:

for (let i = 0, length = array.length; i < length; i++){
  console.log(i);
}

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" :

const true  = !0;
const false = !1;
const alsoFalse = !!0;
console.log(true); // Result: true
console.log(typeof true); // Result: "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 "" .

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

Convert a string to number

Using the addition operator + .

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

May also be used to convert booleans to numbers, as below:

console.log(+true);  // Return: 1
console.log(+false); // Return: 0

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 .

const int = ~~"15"
console.log(int); // Result: 15
console.log(typeof int); Result: "number"

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)

import React, { Component } from React;

export default class App extends Compononent {
    constructor(props) {
      super(props);
      this.state = {};
    }

  myMethod = () => {
    // This method is bound implicitly!
  }

  render() {
    return (
      <>
        <div>
          {this.myMethod()}
        </div>
      </>
    )
  }
};

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.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

Last updated