js

Save your time with these modern 5 Java script tips and tricks

Posted by
Share this post

Programming has no exact way to do things; almost everything can be done in multiple ways. However, there are some tips and tricks that can help save your time and speed up the process. Below are 5 time-saving tips that will be useful and helpful in cutting off your extra time.

1. Object Destructing :

Introduced in the ES6, destructing is one such feature that quickly accesses and uses the values in objects.You will use it daily once you understand how. 

It helps you deal with three main issues :

  • Repetition. You create a new line, every time you want to extract one object property and create a new variable. 
const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

// Wow... should we display
// John's password like that?

const firstName = user.firstName;
const lastName = user.lastName;
const password = user.password;
  • Accessibility. Each time you want to access an object property, you should write the path to it. (example: user.firstNameuser.family.sister, and so on).
  • Usage. When creating a new function, it enables you to work with a single property of an object.

Here’s how you can solve these three issues.

  • Repetition: Destructing extracts a property from an object by its key. Take an existing key in your object and then place it between two brackets ({ firstName }) inform JavaScript that you want to create a variable with the same name as your property. Further, go on creating a variable firstName for the firstName property of the object.

(Pro tip: If you want to destructure an object, always use an existing key. Otherwise, it will not work.)

const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

const { firstName, lastName, password } = user;

console.log(firstName, lastName, password);
// Output: 'John', 'Doe', '123'
  • Accessibility: It becomes quite repetitive when working with nested objects. This wastes a lot of time accessing the same property many times. Using destruction just in a single line can reduce the property path to one variable.
const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
  family: {
    sister: {
      firstName: "Maria",
    },
  },
};

// We access to the nested object `sister`
// and we extract the `firstName` property
const { firstName } = user.family.sister;

console.log(firstName);
// Output: 'Maria'
  • Usage: Now that you know how to destructure an object, here’s how you can extract properties directly in your function parameter definition. If you know React, you’re already familiar with it. Rather than passing the whole object or creating a new variable, you can simply destructure the object’s function parameters.
function getUserFirstName({ firstName }) {
  return firstName;
}

const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

console.log(getUserFirstName(user));
// Output: 'John'

2. How to merge objects in ES6

Data structures are often challenging during programming. But, thanks to the spread operator introduced in ES6 that makes the object and array manipulations more straightforward.

const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

const userJob = {
  jobName: "Developer",
  jobCountry: "France",
  jobTimePerWeekInHour: "35",
};

Let’s imagine that we have two objects :

  • User. An object defining general information about the user.
  • UserJob. An object defining job information of the user.

We want to create one object that contains the properties of these two objects. Here a spread operator (…), can help us extract all the properties of one object to another.

const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

const userJob = {
  jobName: "Developer",
  jobCountry: "France",
  jobTimePerWeekInHour: "35",
};

const myNewUserObject = {
  ...user,
  ...userJob,
};

console.log(myNewUserObject);
// Output:
//{
//  firstName: 'John',
//  lastName: 'Doe',
//  password: '123',
//  jobName: 'Developer',
//  jobCountry: 'France',
//  jobTimePerWeekInHour: '35'
//}

Using the spread operator (…), we can extract all the properties of one object to another.

const user = {
  firstName: "John",
  lastName: "Doe",
  password: "123",
};

const myNewUserObject = {
  ...user,
  // We extract:
  // - firstName
  // - lastName
  // - password
  // and send them to
  // a new object `{}`
};

3. How to Merge Arrays 

const girlNames = ["Jessica", "Emma", "Amandine"];
const boyNames = ["John", "Terry", "Alexandre"];

const namesWithSpreadSyntax = [...girlNames, ...boyNames];

console.log(namesWithSpreadSyntax);
// Output: ['Jessica', 'Emma', 'Amandine', 'John', 'Terry', 'Alexandre']

The spread operator (…) extracts all the elements from one array to another, the same way it does with objects.

4. How to Remove Array Duplicates

If you want to remove duplicates in your array, you can follow one of the examples below. Below are two examples that will help you compare: the old way and the new way.

  • How to remove array duplicates “the old way”
const animals = ["owl", "frog", "canary", "duck", "duck", "goose", "owl"];

const uniqueAnimalsWithFilter = animals.filter(
  // Parameters example: 'owl', 0, ['owl', 'frog', 'canary', 'duck', 'duck', 'goose', 'owl']
  (animal, index, array) => array.indexOf(animal) == index
);

console.log(uniqueAnimalsWithSet);
// Output: ['owl', 'frog', 'canary', 'duck', 'goose']

Let’s consider the above example where we want to clean the animals array by removing all duplicates. The old way used the function filter with indexOf inside it. The filter function takes all elements of the animals array (animals.filter) and with each occurrence provides :

  • the current value (example: duck)
  • the index (example: 0)
  • the initial array (example: the animals array => [‘owl’, ‘frog’, ‘canary’, ‘duck’, ‘duck’, ‘goose’, ‘owl’])

Later we will apply index0f on the original array for each occurrence and give a parameter for the animal variable (the current value). 

Then the index0f will return the first index of the current value (example: for ‘owl’ the index is 0).

Next, we compare the value of index0f to the current index inside of the filter. If it’s the same, we return true otherwise false.

Hence, the filter will create a new array with only the elements where the returned value was true.

So, in our case: [‘owl’, ‘frog’, ‘canary’, ‘duck’, ‘goose’].

  • How to remove array duplicates “the new way”

The old way is interesting but is a bit complicated, let’s learn the new way now. 

const animals = ["owl", "frog", "canary", "duck", "duck", "goose", "owl"];

const uniqueAnimalsWithSet = [...new Set(animals)];

console.log(uniqueAnimalsWithSet);
// Output: ['owl', 'frog', 'canary', 'duck', 'goose']

Let’s separate out the different steps :

// 1
const animals = ["owl", "frog", "canary", "duck", "duck", "goose", "owl"];

// 2
const animalsSet = new Set(animals);

console.log(animalsSet);
// Output: Set { 'owl', 'frog', 'canary', 'duck', 'goose' }

// 3
const uniqueAnimalsWithSet = [...animalsSet];

console.log(uniqueAnimalsWithSet);
// Output: ['owl', 'frog', 'canary', 'duck', 'goose']

We have an animals array, and we convert it into a Set, a special type of object in ES6. What’s different here is this way lets you create a collection of unique values.

(Note : Set is a collection of unique values, but it’s not an Array.)

Once we have our Set object with unique values, we need to convert it back to an array. To do that, we use the spread operators to destructure it, which sends all the properties to a new Array. As the Set object has unique properties, our new array will also have unique values.

 5. How to Use Ternary Operators

Have you already heard about a way to write small conditions in a single line? If not, it’s time to remove a lot of if and else blocks and converts them to small ternary operations. Let’s look at an example with console.log to start. The idea is to check the value of a variable and conditionally display an output.

const colour = "blue";

if (colour === "blue") {
  console.log(`It's blue!`);
} else {
  console.log(`It's not blue!`);
}

One line to rule them all!

const colour = "blue";

colour === "blue" ? console.log(`It's blue!`) : console.log(`It's not blue!`);
// [condition] ? [if] : [else]

 This example is a typical case where you can use the ternary operator to reduce these 5 if and else lines to only one! Ternary operators replace if and else for small conditions.

(Note:  It’s not recommended to create complex conditions with ternary operators because it can reduce readability.)

Below is another example that uses ternary operators, but this time in the return of a function.

function sayHelloToAnne(name) {
  return name === "Anne" ? "Hello, Anne!" : "It's not Anne!";
}

console.log(sayHelloToAnne("Anne"));
// Output: 'Hello, Anne!'

console.log(sayHelloToAnne("Gael"));
// Output: "It's not Anne!"

Conclusion

I hope this post helped you learn some new things about JavaScript. Stay in touch for more new updates!

No ratings yet.

Please rate this