DEV Community

Dawn Zhao for MarsCode

Posted on

5 Javascript Tips You Should Know

Written by Joab Chua

1. Console.log

  • Add colour to your console log

Stop doing just this! ❌

Image description

Image description
Try this instead. ✅

Image description

Image description
But if you have an array of objects, try this would be even better 😎

Image description

Image description
If you want to measure how fast certain operations run in your code, try this.

Image description

Image description
Do console.time and console.timeEnd to measure the time taken in the browser console.
Lastly, if you want to trace your code and its execution sequence, try this.

Image description

Image description
You will be able to see tonnes of info that you need to debug your application.

2. Object de-structuring

Image description
Did it happened to you before that you only need a few variables in the object but you are being passed the full object and using it in this conventional way?

Image description
Repeatedly using the human object declaration in your function? Don’t do this. Use ES6 object de-structuring instead. ✅

Image description
De-structure the variables that you need to use in the function arguments. Alternatively, you can de-structure inside the function itself.

Image description

3. Template Literal

❌ Don’t do this when you are trying to piece your variables with string.

Image description
Do this instead. ✅
Image description

4. Spread operator

Let’s say you have 2 object and you want to combined them or assign some of the properties of 1 object to another. Traditionally, we will do this.
Image description
There is technically nothing wrong with that, except that you are actually mutating your object. Try this instead. ✅
Image description
Best thing of spread operator is that it works for array as well. 😎
Instead of this.
Image description
Do this instead.
Image description

5. loops

Are you guilty of doing for loop this way to calculate the total amount of the cost in an array? Stop doing this. ❌
Image description
Start to change your style to this instead.
Image description
Clean and lean. Job done! ✅

Summary

Hope that these few tips will guide you along to write better, cleaner and leaner code.

Sponsored by MarsCode
Welcome to join our Discord to discuss your ideas with us.

Top comments (0)