5 Modern JavaScript Tips and Tricks To Save Time

5 Modern JavaScript Tips and Tricks To Save Time

Reduce workload and write clean code using these JavaScript tips

Photo by [Jamie Street](https://cdn.hashnode.com/res/hashnode/image/upload/v1630754110044/5jW_L5YhH.html) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)Photo by Jamie Street on Unsplash

When it comes to programming, there is no one correct way to do things. Almost everything can be done in multiple ways.

However, there are some tips and tricks you should keep in mind to speed up the process.

Below are 5 tips and tricks that you will hopefully find useful.

1. Merging Objects and Arrays

To merge objects, the standard way can lead to a lot of hassle. Thus, we would be using the spread operator introduced in the ES6 update.

Using the spread operator greatly simplifies the merging process.

const person = {
  firstName: "John",
  lastName: "Doe",

};

const job = {
  role:'Developer',
  level:'Senior'

};

let myPerson  = {
  ...person,
  ...job
};

console.log(myPerson);

The output of the code snippet above:

{
  firstName: "John",
  lastName: "Doe",
  level: "Senior",
  role: "Developer"
}

But what if there exists the same key in two or more objects?

In that case, the last object’s key’s value is considered and put in the merged object.

const person = {
  firstName: "John",
  lastName: "Doe",

};

const person1 = {
 firstName: "Smith",
  lastName: "Doe",

};

let myPerson  = {
  ...person,
  ...person1
};

console.log(myPerson); // => {firstName: "Smith",lastName: "Doe"}

We can merge arrays using the same technique.

const person = ["John", "Felix"];
const job = ["Accountant"];

const mergedArray = [...person, ...job];

console.log(mergedArray); // => ["John", "Felix", "Accountant"]

If you are interested in knowing more about different array methods, you can check out the article given below: 8 Modern Array Methods that Every Developer Should Know Incredibly useful methods to make your life easiermedium.com

2. Utilising the consoleobject properly

Using the console object, you can log important debugging messages.

However, logis just one of the amazing methods offered by the console object.

Using console.warn() you can throw warnings while the console.clear() the method allows you to clear the console log.

You can even measure the time your code took to run using the console object!

const person = ['John', 'Felix'];
const job = ['Accountant', 'Developer'];
const mergeThings = function () {
  const mergedArray = [...person, ...job];
};
mergeThings();
console.timeEnd('mytime'); // => mytime: 1ms

As you can see, wrapping the code you want to measure the time of with console.time() and console.timeEnd() methods will enable you to log the time.

It is worth mentioning that you need to pass the same string as the parameter in both methods.

You can even group messages, create tables as well as style the logs using the methods provided by the console object. To find a comprehensive guide for the same, you can go here.

3. Destructuring

Another feature introduced in the ES6 update is the ability to destructure objects easily.

You can quickly access and use the values in objects using destructuring.

const person = {
  name: 'Kevin',
  job: {
    role: 'Developer',
    position: { level: 'Senior', experience: '10 yrs' },
  },
};
const {experience}=person.job.position
console.log(experience) // => "10 yrs"

From the above code snippet, you can see that we can extract values from a particular key-value pair by wrapping the key with brackets.

We can even extract multiple values using the same technique as shown below:

const user = {
  firstName: "Kevin",
  lastName: "Goodman",
};

const { firstName, lastName } = user;

console.log(firstName, lastName); // => "Kevin Goodman"

That’s not all though.

We can even use the same method in functions, enabling them to only accept relevant values as parameters.

function getHobby({ hobby }) {
  return hobby;
}

const user = {
  firstName: "Kevin",
  lastName: "Smith",
  hobby: "Football",
};

console.log(getHobby(user)); // => "Football"

In the code above, we can see that the usage of destructuring to only get the ‘hobby’ key value as a parameter.

This leads to a more cleaner and robust code.

4. Ternary Operator

Although JavaScript offers plenty of ways such as if-else and switch-case to check if a particular condition is met, these checks can be written in a much shorter way using the ternary operator.

For instance, we want to check if the day is Monday and display the message accordingly.

Using the if-else our code would look something like this:

let day = 'Monday';
if (day == 'Monday') {
  console.log('It is Monday');
} else console.log('It is not Monday');

However, we can shorten the code as well as enhance the readability using ternary operators.

let day = 'Monday';

day=='Monday' ? console.log('It is Monday'):console.log('It is not Monday')

Using the ternary operators ? and : , we can replace the if-else code blocks.

Although ternary operator works great for small comparisons, it is not ideal for long and complex comparisons as they reduce the readability.

5. Quick Conversions

Many times we want to convert a string into a number or vice versa and perform some operators thereafter.

Below are a few ways to quickly convert the datatype of variables.

Converting to String

String is probably the easiest to convert to.

const num= 1 + "";

console.log(num); // => "1"
console.log(typeof num); // => "string"

Converting to Integer

To convert to an integer, we use the + operator to tell JavaScript to convert the string to a number.

let num= "1";
num= +num;

console.log(num); // => 1
console.log(typeof num);// => "number"

Converting to Boolean

JavaScript assigns a true or false value to all the variables.

0, "", null, undefined, NaN and of course false are considered as false by JavaScript while all other values are true.

With this in mind, we can simply convert variables to booleans.

const mTrue  = !0; //true
const mFalse = !1; //false
const qFalse = !!0; // false

By using the ! operator, we can switch between the true and false values of variables.

**Conclusion**

As JavaScript is being used to create increasingly complex apps, it is wise to have a few tips and tricks in hand to ease the development process.

Moreover, one must know and follow some of the modern practices of JavaScript.

I have a blog on some of the modern practices of JavaScript which is worth taking look over whether you are a noob or a pro.

With JavaScript, you get the flexibility of doing the same task in more than one way.

However, using these practices and tips can drastically reduce your workload as well as help you crack interviews and build better apps.

Enjoyed this article? If so, get more similar content by **subscribing to our YouTube channel!**

Did you find this article valuable?

Support Smart Dev Blogs by becoming a sponsor. Any amount is appreciated!