Best 8 Useful JavaScript Tricks in 2019

Best 8 Useful JavaScript Tricks in 2019
In this article, I will show you best 8 useful JavaScript tricks in 2019 I find useful. Some of them I've used in practice and others are the new way of solving old problems.

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.

1. Ensure Array Values

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) ["", "", "", "", ""]

2. Get Array Unique Values

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

3. Merge Objects and Array of Objects Using Spread Operator

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"
*/

4. Map the Array (without the Array.map)

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"]

5. Conditional Object Properties

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]' } : null)
  }
}

const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "[email protected]" }

const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }

6. Destructuring the Raw Data

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: "[email protected]", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45 }

7. Dynamic Property Names

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: "[email protected]" }

8. String Interpolation

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

Conclusion

JavaScript world is expanding rapidly. A lot of cool features are here and ready to be used. Problems that were tricky and time-consuming are slowly fading into the past, and with ES6 new features, the solutions are provided out of the box.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

12 tips for writing clean and scalable JavaScript

10 JavaScript Charting Libraries for Every Data Visualization Need

Suggest:

Here are 380 Ivy League courses you can take online right now for free

Most Popular JavaScript Frameworks 2019 - I'm Programmer

Building a Video Blog with Gatsby and Markdown (MDX)

How to check if Checkbox is Checked or not using Plain JavaScript

A Beginner Guide To Node.js (Basic Introduction To Node.js)

How to create Restful CRUD API with Node.js MongoDB and Express.js