loading...
Cover image for 7 JavaScript Hacks for 2020

7 JavaScript Hacks for 2020

_patrickgod profile image Patrick God Updated on ・6 min read

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.

const hero = {
    name: 'Spiderman',
    firstName: 'Peter',
    lastName: 'Parker',
    city: 'New York City'
};

console.log(hero);

console.log('hero', hero);

console.log() with a label

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.

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()

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.

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

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

function multiply(x, y, z) {
    return x * y * z;
}

const numbers = [2, 3, 4];

console.log(multiply(...numbers));

Spread Syntax Multiplication

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.

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

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.

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

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

superHeroes = [...superHeroes, 'Batman'];
console.log(superHeroes);

Append arrays

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.

let heroes = [
    ['Superman', 'Batman', 'Wonderwoman'],
    ['Spiderman', 'Iron Man', 'Hulk']
]

console.log(heroes.flat());

Flatten array

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.

let heroes = [
    ['Superman', 'Batman', 'Wonderwoman'],
    [
        ['Spiderman', 'Amazing Spiderman'],
        'Iron Man', 'Hulk'
    ]
]

console.log(heroes.flat());
console.log(heroes.flat(Infinity));

Flatten arrays to infinity

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.

const isBatman = true;

function printBatman() {
    console.log("I'm Batman!");
}

if (isBatman) {
    printBatman();
}

isBatman && printBatman();

isBatman && console.log("I'm Batman!");

Short-Circuiting

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.

const hero = { name: 'Batman' };

console.log("I'm " + hero.name + "!");

console.log(`I'm ${hero.name}!`);

Template Literals

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:

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()

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.

marvel.map(h => h.team = 'Avengers');

console.table(marvel);

map()
If we had an array of numbers, we could multiply every number with itself and the results are stored in a new array.

const numbers = [2, 4, 6, 8];
const multi = numbers.map(n => n * n);
console.log('numbers', multi);

map() with numbers

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.

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

reduce()

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

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

Happy coding!


But wait, there’s more!

Posted on by:

_patrickgod profile

Patrick God

@_patrickgod

Into code as long as I can remember. First games, then web, now both. Located in the sweet Taunus-region in Germany. Always eager to learn, create and teach something new.

Discussion

markdown guide
 

Those are features, not hacks 🤨

 

True. Thanks for pointing that out. I just thought, "hacks" sounds nice. ;)

 

Nice list and the coolest thing is that it's perfectly safe to use, it's not hacky !

For the console.log with template literals, I like to do the following instead :

console.log("I'm %s", hero.name);

🤓

But I'm kidding I know you are talking about the general use not console.log in particular.

 

In article the Styling Console Messages I used

console.log('%cStyling Console Messages', 'color:green; background:#33eeaa; font-size:25px;')

Styling console message is makes debugging easier.

 

Hey Julien,

Thank you. And thank you for the other way of using console.log(). You can even colorize the console with console.log(). It's crazy what you can do nowadays. :D

Take care,
Patrick

 

I think console.log({hero}) is a better way than console.log('hero', hero'). I use it all the time, thought you would like it ;)

Nice post

 

That's great! Thank you! :)

 

A good summary of the js features ES5/6. Those are very useful. I liked the part to use filter, map and reduce.

Thanks.

 

Thank you very much. :)

 

This is simply great. Thanks a lot for sharing with us those features. I am a beginner and i only know to use the console for debugging and now It will be easier.

 

Thank you! Glad I could help. :)