11 JavaScript Tricks – You may not be able to find them in Tutorials

Tram Ho

This article is intended to be helpful for beginners on 11 concise ways to write more concise and efficient JavaScript code. Let’s begin to learn the 11 ways to write it!

Filter Unique Values


ARRAYS

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.

This trick works for arrays that contain primitive types: undefined , null , boolean , string and number . (If you have an array containing additional objects, functions, or arrays, you’ll need a different approach!).

Short-Circuit Evaluation


CONDITIONALS

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

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use && , and || logical operators to evaluate certain expressions in an even more concise manner. This is often referred to as short-circuiting or short-circuit evaluation .

How It Works

Now you want to return only one or two options.

Using && will return the first false or falsy . If all the evaluated operands are true , the last evaluated expression will be returned.

Use || will return true or truthy first. If all the operands evaluate to false , the last evaluated expression will be returned.

Example 1

Next you want to return độ dài of a variable, but you don’t know the type of variable.

We can use the if/else to check if foo is an acceptable type, but this can be quite long. Short circuit evaluation allows you to do this instead:

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

Example 2

Have you ever had problems accessing a nested object attribute? You may not know whether the object or one of the extra properties exists and this can cause annoying errors.

Now you want to access an attribute called data in this.state , but the data is not defined until your program returns the fetch request successfully.

Depending on where you use it, calling this.state.data may prevent your application from running. To solve this problem, we can package it in one condition:

But that seems quite repetitive. Operator || Provide a more concise solution:

You can refactor the code above to use && . Statement Fetching Data && this.state.data returns this.state.data whether it undefined or not. This is because Fetching Data is truthy, and so && will always pass it when listed first.

Convert to Boolean


TYPE CONVERSION

Besides the usual boolean values ​​of true and false , JavaScript also treats all other values ​​as truthy or falsy .

Unless otherwise specified, all values ​​in JavaScript are truthy except for 0 , "" , null , undefined , NaN and of course false , that is falsy .

We can easily switch between true and false using the negative operator ! , will also convert the type to "boolean" .

This type of conversion can be useful in conditional statements.

Convert to String


TYPE CONVERSION

To quickly convert a number into a string, we can use the + concatenation operator followed by a set of "" blank quotes.

Convert to Number


TYPE CONVERSION

The opposite can be quickly achieved using the plus + operator.

This can also be used to convert booleans into số , as follows:

There may be contexts where the + sign will be interpreted as a concatenation operator instead of a plus operator. When that happens (and you want to return an integer, not a float), you can instead use two tildes: ~~ .

The tilde, called bitwise NOT operator , is the bitwise NOT operator equivalent to -n-1 . So for example: ~15 equals -16 .

Using two consecutive tildes will effectively remove the operation, because -(-n - 1) - 1 = n + 1 - 1 = n . In other words, ~-16 equals 15 .

The bitwise NOT operator can also be used on booleans: ~true = -2 and ~false = -1 .

Quick Powers


OPERATIONS

Since ES7, it is possible to use the power operator ** , faster than writing Math.pow (2, 3) . This is a simple tool, but it doesn’t have a lot of updated instructions to include this operator!

This should not be confused with the ^ symbol, which is often used to denote exponents, but in JavaScript is the bitwise XOR operator.

Before ES7, when working with exponents, the left shift operator << would be used:

Example 2 << 3 = 16 will be equivalent to 2 ** 4 = 16 .

Quick Float to Integer


OPERATIONS / TYPE CONVERSION

If you want to convert a float to an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to truncate a float into an integer using | , the bitwise OR operators.

Use | will work differently depending on whether you’re working with positive or negative numbers, so it’s only best to use this shortcut if you’re sure.

If n positive, n | 0 will round the result down. If n negative, it rounds the result up. More precisely, this will remove anything after the decimal point, truncating a float to an integer.

You can get the same rounding effect by using ~~ , as above and in fact, any bitwise operator will force a float to an integer. The reason these specific operations work is: Once forced into an integer – The value will be preserved.

Delete the last digits

The bitwise OR operator can also be used to remove any number of digits from the end of an integer. This means you don’t have to use like this to switch between types:

Instead, the bitwise OR operator allows us to write:

Automatic Binding in Classes


CLASSES

We can use the ES6 arrow notation in Class methods and that way the implications are implied. This will usually save a few lines of code in the Class constructor and we can happily say goodbye to repeated expressions like this.myMethod = this.myMethod.bind(this) !

Truncate an Array


ARRAYS

If you want to remove the values ​​from the end of an array thoroughly, there are faster alternatives than using splice() .

For example, if you know the size of the original array, you can redefine its length attribute, like so:

This is a particularly concise solution. However, the run time of the slice() even faster. If speed is your main goal, consider using something like this:

Get the Last Item (s) in an Array


ARRAYS

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

JSON Code Format


JSON

Lastly, you may have used JSON.opesify() before, but did you realize that it can also help you indent JSON?

The stringify() has two optional parameters: an alternative function you can use to filter displayed JSON and space values.

The space value takes 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 a lot easier.

Conclude


Hopefully this article will help you somewhere when working with JavaScript, thank you for reading the article 😀

The article is referenced from https://medium.com/@bretcameron/12-javascript-tricks-you-wont-find-in-most-tutorials-a9c9331f169d

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo