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);
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');
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);
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));
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);
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);
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);
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());
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));
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!");
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}!`);
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);
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);
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);
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));
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!
- Let’s connect on Twitter, YouTube, LinkedIn or here on dev.to.
- Get the 5 Software Developer’s Career Hacks for free.
- Enjoy more valuable articles for your developer life and career on patrickgod.com.