Some neat coding tips in JavaScript

Tram Ho

Sometimes the standard syntax of the code will make functions long and cumbersome, so we often shorten the code with tips (tricks) without affecting the results. With experienced developers, these tips are already available in their code thinking with years of major projects and accumulations.

And also in Javascript, so I would like to summarize some tips, tricks of the Dev / you go ahead for the beginners to approach. Let’s get started!

JSON Code Format

You may have used JSON.stringify before, but have you realized that it can also help you with a nicer format when outputting? The stringify () method has two optional parameters:

  • replacer function , you can use to filter the displayed JSON and space values.
  • space helps you get an integer for the number of spaces you want or a string (such as ‘ t’ to insert tabs) and it can make reading JSON data much easier to fetch.

Get the Last Item (s) in an Array

The method in the array is slice () that can take negative integers and if provided, it will take values ​​from the end of the array instead of starting.

Filter Unique Values

The Set object type was introduced in ES6 and together with …, the ‘spread’ operator, we can use it to create a new array with only unique values.

Ternary Operator – Triple operator

We have the if … else code as follows:

is abbreviated as follows:

Shorthand Evaluate

When assigning a variable’s value to another variable, we often want to make sure that the variable’s value is not null , not undefinded or empty , so it’s necessary to write a series of conditions to check:

is abbreviated as:

Function Declaration

The old type of function declaration is easy to read and write, but it becomes confusing when combined with other function calls. For example instead of:

You can use arrow syntax to declare the function (arrow function):

Destructuring Assignment

If you have worked with js frameworks, it is not uncommon to transfer data in the form of objects between components. When the data object is transferred, we need to unpack it.

The above paragraph is shortened as:

And many more …

summary

Above, I have shared some tips to help newbie like me, or the older ones who have not used it, they can apply immediately to their projects. Thank you for watching, wish you good study!

Share the news now

Source : Viblo