# 12 JS Tricks

## 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.

```javascript
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
```

```javascript
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:

```javascript
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:

```javascript
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"`** :

```javascript
const true  = !0;
const false = !1;
const alsoFalse = !!0;
```

```javascript
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  `""`** .

```javascript
const val = 1 + "";
```

```javascript
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"
```

## Convert a string to number

Using the **addition operator `+`** .

```javascript
let int = "15";
int = +int;
```

```javascript
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
```

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

```javascript
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` .

```javascript
const int = ~~"15"
```

```javascript
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`&#x20;

## Automatic Binding in Classes

By **using arrow notation in class methods binding is implied**.

Avoiding repetitive expressions like `this.myMethod = this.myMethod.bind(this)`&#x20;

```javascript
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.

```javascript
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
```

```javascript
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ricardomol.gitbook.io/notes/frontend/untitled/articles/12-js-tricks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
