Tips and Tricks in Javascript
Tags: javascript, webdev, beginners, productivity
Published: 2021-06-09 03:31:05

In this article, let us cover some tips and tricks of Javascript everyone should be aware of.

## Convert to boolean

All values in javascript are `truthy` except for `0`, `""`, `null`,`undefined`, `NaN` and of course `false`.

We can easily switch between `true` and `false` by using the negative operator(`!`), which also converts the type to **boolean**.

```js
console.log(!0); //true
console.log(!1); //false
console.log(!!0); //false
console.log(!undefined); //true
```

Amazing right?

## Convert to Number

Converting to number can be easily achieved using the **addition operator** (`+`).

```js
let num = "10";
console.log(num); // "10"
console.log(typeof num); // "string"

num = +num;

console.log(num); // 10
console.log(typeof num); // "number"
```

How cool is that?

## Quick float to integer

There are several ways to convert **float to an integer** by using `Math.floor()`, `Math.ceil()` or `Math.round()`, but there is also a quicker way to convert a **float to an integer** by using the **bitwise OR operator** (`|`).

```js
console.log(11.5 | 0); // 11
console.log(-11.5 | 0); // -11
```

> Wow! Amazing right? I started using this more frequently now.

## Short-Circuit Evaluation

### Using &&

Using `&&` will return the first `false` or `falsy` value. If every operand is expected to be `true`, then the last evaluated expression will be returned.

```js
console.log(true && true && 2); // 2
console.log(true && false && 2); // false
```

### Using ||

Using `||` will return the first `true` of `truthy` value. If every operand is expected to be `false`, then the last evaluated expression will be returned.

```js
console.log(true || false || 2); // true
console.log(false || false || 2); // 2
```

Short-Circuit evaluation is widely used in any programming language.

## Filter unique values from an array

You can easily find **unique values** using the `Set` data structure. The **Set** was introduced in **ES6** along with the spread operator (`...`). Let us use both the new concept to filter unique values of an array.

> I know you'll use this a lot. You can thank me later. 😄

```js
let arr = [1, 1, 2, 3, 4, 4, 5, 2, 3, 6];
const uniqueArr = [...new Set(arr)];

console.log(uniqueArr); // [ 1, 2, 3, 4, 5, 6 ]
```

## Self calling function or IIFE

**IIFE - Immediately Invoked Function Expression**

This is often called as **Self-Invoked Annonymous Function** or **IIFE**. It is a function that executes automatically when it gets created.

```js
(function () {
  console.log("I am running automatically");
})();

//I am running automatically
```

You can read more about **IIFE** <a  href="https://pratapsharma.in/javascript-interview-questions/#explain-why-the-following-doesnt-work-as-an-iife-code-classlanguage-textfunction-foo-code-what-needs-to-be-changed-to-properly-make-it-an-iife" target="_blank">here</a>.

## Get a random item from an array

We can use `Math.random()` and `Math.floor()` methods to get a random item from an array.

```js
let names = ["Pratap", "Prasar", "Sudip", "Shiva"];

let randomName = names[Math.floor(Math.random() * names.length)];
```

> It is also one of the most commonly used tricks.

## Primitive operations can be faster than function calls

Keep in mind that primitive operations can be faster than function calls.

Instead of using

```js
const min = Math.min(a, b);
```

use

```js
const min = a < b ? a : b;
```

## Empty an array

You can empty an array using the `array.length` property.

```js
let dumarray = [1, 1, 2, 3, 4, 5, 6, 7];
dumarray.length = 0;

console.log(dumarray); // []
```

## To sum it up

This is it from this article. I hope I'm able to help you with top Javascript tips and tricks.

💌 If you'd like to receive more tutorials in your inbox, you can sign up for the newsletter [here](https://pratap.substack.com).

Please don't hesitate to drop a comment here if I miss anything. Also, let me know if I can make the post better.