7 JavaScript Hacks for 2020
Tags: javascript, beginners, tutorial, webdev
Published: 2020-01-06 14:33:44

---
title: 7 JavaScript Hacks for 2020
published: true
description: These JavaScript hacks help you conquering your JavaScript challenges in 2020. Enjoy!
tags: javascript, beginners, tutorial, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/nzno1yflnjqy15w8ju5c.jpg
---
JavaScript has evolved tremendously and there's almost no way around it. It's good to know one or two hacks that make your developer's life a bit easier.

Let’s start with something simple. Of course, `console.log()` is nothing new to you. For a long time, I simply used `console.log()` and then just entered the object I wanted to see. It was already a relieve when I found out that you could enter a label in front of an object.

```javascript
const hero = {
    name: 'Spiderman',
    firstName: 'Peter',
    lastName: 'Parker',
    city: 'New York City'
};
 
console.log(hero);
 
console.log('hero', hero);
```

![console.log() with a label](https://thepracticaldev.s3.amazonaws.com/i/ba28o7hvov5zpz9e8iu2.jpg)

# 1. Time measurement/performance tracking

That’s not a big deal, of course. But logging in the console evolved. Recently I had to optimize the performance of an application. Instead of creating a `Date` object and calculating the time with that, you can simply use `console.time()`.

With `console.time('myTimer')` you start a timer. With `console.timeLog('myTimer')`  you can log the current time and with `console.timeEnd('myTimer')` you end the timer and display the elapsed time. Pretty neat.

```javascript
console.time('factorial');
 
const number = 10;
let result = 1;
for (let i = 1; i <= number; i++) {
    result *= i;
    console.timeLog('factorial');
}
 
console.log('factorial result', result);
console.timeEnd('factorial');
```
![Factorial with console.time()](https://thepracticaldev.s3.amazonaws.com/i/tm23lqfhq1y8hh4ptfk4.jpg)

# 2. Table logging

Apart from logging the elapsed time I found another function useful, which is `console.table()`. It’s not unlikely that you get data from a service call that you want to display in the console. If said data is an array of objects with the same properties, you can display them as a table. Better overview, easier debugging.

```javascript
const heroes = [
    {
        name: 'Spiderman',
        firstName: 'Peter',
        lastName: 'Parker',
        city: 'New York City'
    }, {
        name: 'Iron Man',
        firstName: 'Tony',
        lastName: 'Stark',
        city: 'New York City'
    }];

console.table(heroes);
```

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jj2dns6hyy6hj1uorjnt.jpg)

#  3. Spread Syntax
Next is the spread syntax. In essence, it’s three periods followed by an object or array. You can use this expression wherever an arbitrary number of arguments or elements are expected.

##Multiplication

```javascript
function multiply(x, y, z) {
    return x * y * z;
}
 
const numbers = [2, 3, 4];
 
console.log(multiply(...numbers));
```
![Spread Syntax Multiplication](https://thepracticaldev.s3.amazonaws.com/i/idrslzofui9xa9r6bykj.jpg)

The function expects three arguments, but we can also give it an array of three numbers. We can still call the function with the spread operator and see the correct result.

##Set (extract unique values)

Another useful feature is to extract unique values from an array. Let’s say we have an array of names or numbers. With the spread operator and the type `Set`, we can return only the unique names or numbers, respectively.

```javascript
const names = ['Tony', 'Peter', 'Bruce', 'Bruce', 'Peter', 'Peter'];
var unique_names = [...new Set(names)];
console.log(unique_names);
 
var entries = [1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 7, 8, 9, 9, 9, 10];
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
```

![Set](https://thepracticaldev.s3.amazonaws.com/i/vqwyqmglqlpgkhy4c4ny.png)

##Add properties to object & append arrays
Another example would be to add properties to an object. Instead of adding properties line by line, we can kind of “overwrite” the given object with the added properties and the spread operator.

```javascript
let batman = { name: 'Batman' };
// batman.firstName = "Bruce";
// batman.lastName = "Wayne";
console.log(batman);
 
batman = { ...batman, firstName: 'Bruce', lastName: 'Wayne' };
console.log(batman);
```
![Add properties to object & append arrays](https://thepracticaldev.s3.amazonaws.com/i/q0dhgbdyc74yos23hp6t.png)
In our case Batman gets a first and last name.

##Append arrays

We can do the same to append further elements to an array. Instead of using `push()` to add elements, the three periods do the job and Batman joins the club of superheroes.

```javascript
let superHeroes = ['Spiderman', 'Iron Man'];
console.log(superHeroes);
 
superHeroes = [...superHeroes, 'Batman'];
console.log(superHeroes);
```

![Append arrays](https://thepracticaldev.s3.amazonaws.com/i/gwht9z65kdqr7ts8gul2.png)

# 4. Flatten (multi-dimensional) arrays

It’s not unlikely that you have multi-dimensional arrays that you want to flatten. It’s pretty easy to do that with the `flat()` method.

Here we have two arrays of superheroes inside another. With `flat()` we have one array with all the heroes on one level.

```javascript
let heroes = [
    ['Superman', 'Batman', 'Wonderwoman'],
    ['Spiderman', 'Iron Man', 'Hulk']
]
 
console.log(heroes.flat());
```

![Flatten array](https://thepracticaldev.s3.amazonaws.com/i/h8e9po4sspwseij5ozn5.png)

It’s important to mention that `flat()` only flattens the first level. If you’ve got deeper nested arrays, you can pass the number of levels to the method. Or you simply pass `Infinity` to flatten all levels.

```javascript
let heroes = [
    ['Superman', 'Batman', 'Wonderwoman'],
    [
        ['Spiderman', 'Amazing Spiderman'],
        'Iron Man', 'Hulk'
    ]
]
 
console.log(heroes.flat());
console.log(heroes.flat(Infinity));
```

![Flatten arrays to infinity](https://thepracticaldev.s3.amazonaws.com/i/qnoilkdr56bowweed9ik.png)

# 5. Short-Circuiting

Short-circuiting is nice but should be used with care because it can be hard to read.

In essence, you can shorten a simple if-statement that results in calling another function.

Let’s say, you are Batman and you want to shout it out to the world. The function below does exactly that, but with short-circuiting, you can do this in one single line, i.e. check if you’re Batman and if so tell everyone.

```javascript
const isBatman = true;
 
function printBatman() {
    console.log("I'm Batman!");
}
 
if (isBatman) {
    printBatman();
}
 
isBatman && printBatman();
 
isBatman && console.log("I'm Batman!");
```

![Short-Circuiting](https://thepracticaldev.s3.amazonaws.com/i/0ot59ijoa0wpli892ux0.png)

# 6. Template Literals

Template literals are a great way to use variables in your string. In the past, you might have built your string with lots of plus (+) symbols, added the variable, then added another string, and so on.

With template literals, you can use backticks and then the dollar sign followed by curly brackets to have one complete and readable statement for your string.

```javascript
const hero = { name: 'Batman' };
 
console.log("I'm " + hero.name + "!");
 
console.log(`I'm ${hero.name}!`);
```

![Template Literals](https://thepracticaldev.s3.amazonaws.com/i/ei4nxgm3nsl296inuz2w.png)

# 6. Loops with .filter(), .map() & .reduce()

As a developer, you have to use loops a lot, obviously. With the methods `filter()`, `map()` and `reduce()` you can leave the for loops aside and manipulate your data in one single line.

We start with `filter()`. As the name implies it filters elements of an array. In this example, we’ve got heroes from Marvel and DC. If we only want to see the Marvel heroes, we can use `filter()` like that:

```javascript
const heroes = [
    { name: 'Spiderman', universe: 'Marvel' },
    { name: 'Iron Man', universe: 'Marvel' },
    { name: 'Hulk', universe: 'Marvel' },
    { name: 'Batman', universe: 'DC' },
    { name: 'Superman', universe: 'DC' },
    { name: 'Wonder Woman', universe: 'DC' },
]
 
const marvel = heroes.filter(h => h.universe === 'Marvel');
 
console.table(marvel);
```
![filter()](https://thepracticaldev.s3.amazonaws.com/i/46a90hnj29vw52yzsmcj.png)

The function `map()` grabs every single element of an array and executes the given expression with that element. For instance, we can add the team property to our Marvel heroes. In our case, they are all part of the Avengers.

```javascript
marvel.map(h => h.team = 'Avengers');
 
console.table(marvel);
```
![map()](https://thepracticaldev.s3.amazonaws.com/i/2952elfuob9x4g4w9qu1.png)
If we had an array of numbers, we could multiply every number with itself and the results are stored in a new array.

```javascript
const numbers = [2, 4, 6, 8];
const multi = numbers.map(n => n * n);
console.log('numbers', multi);
```
![map() with numbers](https://thepracticaldev.s3.amazonaws.com/i/0gn1122d7hay28jl017x.png)

Last not least is `reduce()`. With `reduce()`, we can execute an expression on all the numbers of the array. In this example, we pass an accumulator and the current value of the array. The accumulator is the current result of the whole expression and the current value is the single value the function is working on right now. This means we multiply each element with the next of the array, 2 * 4 * 6 * 8.

```javascript
console.log(numbers.reduce((acc,cur) => acc * cur));
```

![reduce()](https://thepracticaldev.s3.amazonaws.com/i/ww0tvsgvvotx2fqvrb70.png)

That’s it! Short, but hopefully very useful.

You can also watch the code in action in this video:

{% youtube uIeXY9B5ARs %}

Happy coding!


---
### But wait, there’s more!
* Let’s connect on [Twitter](https://twitter.com/_PatrickGod), [YouTube](https://www.youtube.com/channel/UCq8LldVrjqe61KQttZlLW8g), [LinkedIn](https://www.linkedin.com/in/patrickgod) or here on [dev.to](https://dev.to/_patrickgod).
* Get the [5 Software Developer’s Career Hacks](http://patrickgod.com/5-software-developers-career-hacks/) for free.
* Enjoy more valuable articles for your developer life and career on [patrickgod.com](http://patrickgod.com).