11 JavaScript Tricks will be difficult to find in the Tutorials

Tram Ho

1. Unique values ​​in an array

Set object type was present in ES6, and with the ‘spread’ ( ... ) operator, we can construct an array with unique values.

This is more complicated than before ES6, we will inevitably resort to loops with more complex logic This trick works for arrays that contain primitive types: undefined, null, boolean, string and number. (If you have an array containing objects, functions or additional array, you need another approach!)

2. Short-Circuit Evaluation

The tri-operator is a quick way to write simple (and sometimes not so simple) conditional statements, like this:

Sometimes when you code with a three-person operator that is more complicated than necessary, you should use ‘and’ && and ‘or’ || instead. logical operator to evaluate certain expressions in a more concise, concise way. This is commonly referred to as ‘short-circuiting’ or ‘short-circuit evaluation’.

How it works Let’s say I want to return one of two or more options

Using ‘&&’ will return the first value false or ‘falsy’ value. If all evaluate operands are true, the final evaluated expression is returned.

Use || will return either true or the first ‘truthy’. If all operands evaluate to false , the final evaluated expression is returned.

Example 1: Suppose I want to return the length of a variable, but we don’t type the variable. We can use an if / else statement to check if foo is an acceptable type, but this can make the code quite long. The short circuit rating allows us to do this instead:

If the variable foo is truthy, it will be returned. Otherwise, the length of an empty array is returned: 0.

Example 2: Have you ever had a problem accessing nested object properties? You might not know whether an object or one of its sub-properties exists, and this might cause an error.

Let’s say we want to access a property named data in this.state, but the data is undefined until our snippet has data passed in.

Depending on where we use it, calling this.state.data can cause an error. To solve this problem, we can put it in one condition:

So is there a way to keep your brevity less verbose. The answer is yes and very simple

We refactor the code above to use &&. The command ‘Fetching Data’ && this.state.data will return this.state.data whether it is undefined or not. This is because ‘Fetching Data’ is ‘truethy’ and so && will always pass it when it is at the top.

3. Convert to Boolean

Besides the usual boolean values ​​true and false, JavaScript also treats all other values ​​as ‘truthy’ or ‘falsy’. In Javascript the following values ​​will be counted as’ falsy ‘: 0 , "" , null', NaN, undefined . And the remainder will be counted as truethy. We can easily convert between true and false using the negative operator ! , will also convert the type to “boolean”.

4. Convert to String

To quickly convert a number to a string, we can use the concatenation operator + followed by an empty set of “” quotes.

5. Convert to Number

The reverse can be achieved quickly by using the plus + operator.

This can also be used to convert booleans to numbers, like so:

There may be some contexts where + will be interpreted as the join operator rather than the addition operator. When that happens (and you want to return an integer, not a real number), then you can use two tilde signs: ~~ . The tilde, called the ‘NOT bitwise operator’, is an equivalent operator with i -n - 1 . So, for example, ~ 15 equals -16 . Using two consecutive tilde negates the operation effectively, because — ( — n — 1) — 1 = n + 1 — 1 = n . In other words, ~ — 16 = 15 .

Although I can’t think of many use cases, the NOT bitwise operator can also be used on booleans: ~true = -2 and ~false = -1 .

6. Quick Powers

Since ES7, it is possible to use the ‘exponential’ ** operator as a shorthand for ‘exponential’, which is faster than writing Math.pow (2, 3). This is a simple tool, but it is on the list because not many instructions have been updated to include this operator!

This notation should not be confused with the ^ symbol, which is commonly used to denote exponents, but in JavaScript it is the bitwise XOR operator. In previous versions of ES7, using shorthand for exponent could only be used for 2 exponents. Since it can use the left bit shift operator <<.

7. Quick Float to Integer

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there’s also a faster way to truncate a real number to an integer by using the |, the bitwise OR operator.

The behavior of | varies depending on whether you are dealing with positive or negative numbers, so it’s best to only use this shortcut if you are sure. Strictly speaking, this removes anything after the decimal point, truncating the real number to an integer.

Remove the last digits The bitwise OR operator can also be used to remove any number of digits at the end of an integer. This means we don’t have to use code like this to convert between types:

Instead, the bitwise OR operator allows us to write:

8. Automatic Binding in Classes

We can use arrow notation ES6 in class methods and by doing so, binding is implied. This will usually store some code in my constructor class, and I can ignore repeating expressions like: this.myMethod = this.myMethod.bind(this)

9. Truncate an Array

If you want to remove the values ​​from the end of an array thoroughly, there are much faster alternatives than using splice() . For example, if you know the size of your original array, you can redefine its length property, like so:

This is an exceptionally concise solution. However, I find the slice () method runtime to be even faster. If speed is your primary goal, consider using something like this:

10. Get the Last Item (s) in an Array

The slice() array method can take negative integers and, if provided, will get the values ​​from the end of the array, not from the beginning.

11. Format JSON Code

Finally, you may have used JSON.stringify before, but did you realize that it can also help indent JSON for you?

The stringify() takes two optional parameters: an alternative function you can use to filter the displayed JSON and a space value.
The whitespace value takes an integer for the number of spaces you want or a string (such as ‘ t’ for tab insertion), and it can make reading JSON data a lot easier.

Conclusion

The above article presents some tips to help you work with javascript more easily, hope you will apply it well with your projects. Recommended articles: 11 JavaScript Tricks You Won’t Find in Most Tutorials

Share the news now

Source : Viblo