Each programming language has its own tricks up in its sleeve. Many of them are known to developers, and yet some of them are pretty hackish. In this article, I will show you a couple of tricks I find useful. Some of them I've used in practice and others are the new way of solving old problems. Enjoy! https://devinduct.com/blogpost/26/8-useful-javascript-tricks
Ever worked on a grid where the raw data needs to be recreated with the possibility that columns length might mismatch for each row? Well, I have! For ensuring the length equality between the mismatching rows you can use Array.fill method.
let array = Array(5).fill(''); console.log(array); // outputs (5) ["", "", "", "", ""]
ES6 provides a couple of very neat ways of extracting the unique values from an array. Unfortunately, they do not do well with arrays filled with non-primitive types. You can read more about it later at this link Handling Array Duplicates Can Be Tricky. In this article, we will focus on the primitive data types.
const cars = [
'Mazda',
'Ford',
'Renault',
'Opel',
'Mazda'
]
const uniqueWithArrayFrom = Array.from(new Set(cars));
console.log(uniqueWithArrayFrom); // outputs ["Mazda", "Ford", "Renault", "Opel"]
const uniqueWithSpreadOperator = [...new Set(cars)];
console.log(uniqueWithSpreadOperator);// outputs ["Mazda", "Ford", "Renault", "Opel"]
Object merging is not a rare task and there is a great chance you've done this in the past and that you will do it in the future. The difference is that in the past you did most of the work manually, but now and in the future, you will use new ES6 features.
// merging objects
const product = { name: 'Milk', packaging: 'Plastic', price: '5$' }
const manufacturer = { name: 'Company Name', address: 'The Company Address' }
const productManufacturer = { ...product, ...manufacturer };
console.log(productManufacturer);
// outputs { name: "Company Name", packaging: "Plastic", price: "5$", address: "The Company Address" }
// merging an array of objects into one
const cities = [
{ name: 'Paris', visited: 'no' },
{ name: 'Lyon', visited: 'no' },
{ name: 'Marseille', visited: 'yes' },
{ name: 'Rome', visited: 'yes' },
{ name: 'Milan', visited: 'no' },
{ name: 'Palermo', visited: 'yes' },
{ name: 'Genoa', visited: 'yes' },
{ name: 'Berlin', visited: 'no' },
{ name: 'Hamburg', visited: 'yes' },
{ name: 'New York', visited: 'yes' }
];
const result = cities.reduce((accumulator, item) => {
return {
...accumulator,
[item.name]: item.visited
}
}, {});
console.log(result);
/* outputs
Berlin: "no"
Genoa: "yes"
Hamburg: "yes"
Lyon: "no"
Marseille: "yes"
Milan: "no"
New York: "yes"
Palermo: "yes"
Paris: "no"
Rome: "yes"
*/
Did you know that there is another way of mapping the array values which doesn't include the Array.map method? If not, check it out below.
const cities = [
{ name: 'Paris', visited: 'no' },
{ name: 'Lyon', visited: 'no' },
{ name: 'Marseille', visited: 'yes' },
{ name: 'Rome', visited: 'yes' },
{ name: 'Milan', visited: 'no' },
{ name: 'Palermo', visited: 'yes' },
{ name: 'Genoa', visited: 'yes' },
{ name: 'Berlin', visited: 'no' },
{ name: 'Hamburg', visited: 'yes' },
{ name: 'New York', visited: 'yes' }
];
const cityNames = Array.from(cities, ({ name}) => name);
console.log(cityNames);
// outputs ["Paris", "Lyon", "Marseille", "Rome", "Milan", "Palermo", "Genoa", "Berlin", "Hamburg", "New York"]
It's no longer needed to create two different objects based on a condition in order for it to have a certain property. For this purpose, the spread operator is the perfect fit.
const getUser = (emailIncluded) => {
return {
name: 'John',
surname: 'Doe',
...emailIncluded && { email : '[email protected]' }
}
}
const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }
Have you ever worked with an object with too much data in it? I'm pretty sure you have. Probably the most common situation is when we have a user object containing the overall data together with details. Here we can call the new ES destructuring feature to the rescue. Let's back up this with an example.
const rawUser = {
name: 'John',
surname: 'Doe',
email: '[email protected]',
displayName: 'SuperCoolJohn',
joined: '2016-05-05',
image: 'path-to-the-image',
followers: 45
...
}
The object above can be represented in a more contextual manner by splitting into two, like this:
let user = {}, userDetails = {};
({ name: user.name, surname: user.surname, ...userDetails } = rawUser);
console.log(user); // outputs { name: "John", surname: "Doe" }
console.log(userDetails); // outputs { email: "john@doe.com", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45 }
Back in the days, we would first have to declare an object and then assign a property if that property name needed to be dynamic. This was not possible to achieve in a declarative manner. These days are behind us and with the ES6 features, we can do this.
const dynamic = 'email';
let user = {
name: 'John',
[dynamic]: '[email protected]'
}
console.log(user); // outputs { name: "John", email: "john@doe.com" }
Last but not least is the new way of concatenating strings. The use-case where this can really shine is if you're building a template based helper components. It makes dynamic template concatenation a lot easier.
const user = {
name: 'John',
surname: 'Doe',
details: {
email: '[email protected]',
displayName: 'SuperCoolJohn',
joined: '2016-05-05',
image: 'path-to-the-image',
followers: 45
}
}
const printUserInfo = (user) => {
const text = `The user is ${user.name} ${user.surname}. Email: ${user.details.email}. Display Name: ${user.details.displayName}. ${user.name} has ${user.details.followers} followers.`
console.log(text);
}
printUserInfo(user);
// outputs 'The user is John Doe. Email: [email protected]. Display Name: SuperCoolJohn. John has 45 followers.'