11 JavaScript tips you won’t find in most tutorials

Tram Ho

Since I started learning JavaScript, I’ve made a list of time-saving tips that I find in other people’s code, on website challenge codes, and anywhere other than the tutorials I’m using. .

I have built this list since then, and in this article, I will share 11 tips I have chosen for myself that I think is particularly useful. This article will be useful for beginners, but I also hope that even programmers who have experienced for a while will find something new in this list.

The list will be divided into several categories: some tips are easy to use in all cases, some may be more suitable for short-term code challenges / codes than for production code, where it is necessary to be more transparent. brief analysis – you will be the one to classify it!

In no particular order, here are 11 neat ways to write shorter and more efficient code.

1. Filter Unique Values
ARRAYS

Set type object has been introduced in ES6, along with , ‘spread’ operator, we can use it to create a new array of unique values ​​(unique values).

Before ES6, independent unique values ​​would require a lot more code!

This tip applies to arrays containing 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.)

2. Short-Circuit Evaluation
CONDITIONALS

The Ternary operator is a quick way to write simple conditional statements (and can sometimes not be very simple), for example:

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

The way it works
Suppose we want to return only 1 of 2 or more options.

Using && will return false or the first “falsy” value. If each operand evaluates to true , the last evaluated expression will be returned.

Use || will return true or the first “truthy” value. If each operand evaluates to false, the final evaluated expression will be returned.

Example 1:
Suppose we want to return the length of a variable, but we don’t know the variable type.

We can use an if/else to check if the type of foo is accepted, but this can be a bit verbose. Instead, the short circuit evaluation allows us to do this:

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

Example 2:
Have you ever had trouble accessing 1 nested object property? You won’t know if an object or one of the sub-properties exists, and this can cause nasty errors.

Suppose we want to access a property named data inside this.state , but the data is not defined until our program successfully returns a fetch request.

Depending on where we use it, calling this.state.data may prevent our app from running. To solve this problem, we can grab it into a conditional command:

But that also seems a bit repetitive. The ‘or’ operator can resolve it more quickly:

We cannot refactor the code above to equal && . Statement 'Fetching Data' && this.state.data will return this.state.data whether it is undefined or not. This happens because 'Fetching Data' is ‘truthy’, so && will always pass it when it is first listed.

1 new proposed feature: Optional chain – Optional Chaining
There is currently a proposal to enable ‘optional chaining’ when trying to return a property within a ‘tree-like’ structure. As suggested, the question mark icon ? can be used to output a property only if it is not null .

For example, we can refactor the above example to this.state.data?.() , So return data when it is not null .

Or, if we only care about whether the state is defined or not, we can return this.state?.data .

The request command is in Stage 1, as an experimental feature. You can read about it here , and you can use it right in your JavaScript thanks to Babel, by adding @ babel / plugin-proposal-optional-chaining to your .babelrc file.

3. Convert into Boolean
TYPE CONVERSION

Besides the usual boolean values true and false in, JavaScript also treats all other values ​​like ‘truthy’ or ‘falsy’.

Unless they have been specified, all values ​​in JavaScript are ‘truthy’ with the exception of 0 , “” , null , undefined , NaN and of course false , which is “falsy”.

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

This type conversion can be quite handy when dealing with conditional statements, even though the only reason you’ll choose to determine !1 is false if only when you’re playing the code!

4. Convert to String
TYPE CONVERSION

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


5. Convert to Number
TYPE CONVERSION

The opposite can be quickly obtained by addition operator + .

This can also be used to convert booleans into numbers, as shown below:

The + case will operate as a concatenation operator rather than the addition operator, which may occur. Then (and you want to return 1 integer, not 1 real number) you can use 2 tildes: ~~ instead.

A tilde, known as ‘bitwise NOT operator’, is an operator equivalent to -n - 1 . So, for example, ~15 would be equal to -16 .

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

Although I don’t think in most use cases, this bitwise can also be used on booleans: ~true = -2 and ~false = -1 .

6. Quick Powers
OPERATIONS

From ES7, it was possible to use exponential operators ** as shorthand for power, which is faster than writing Math.pow(2, 3) . This is a simple tool, but it is still on the list because not many new updated tutorials include this operator!

This should not be confused with the ^ sign, which is commonly used to represent exponents, but in JavaScript it is a ‘bitwise XOR operator’.

Before ES7, shorthand only existed for power with base 2, using the bitwise left shift operator << :

For example, 2 <<3 = 16 is the same as 2 **4 = 16 .

7. Quick Float to Integer – Quickly convert real numbers to whole numbers
OPERATIONS / TYPE CONVERSION

If you want to convert a real number into an integer, you can use Math.floor() , Math.ceil() or Math.round() . But there is also a faster way to convert a real number into an integer equal to | , it is a ‘bitwise OR operator’.

Behavior of | quite diverse based on whether you are working with positive or negative numbers, so only use this shortcut when you are sure.

If n is positive, n | 0 rounded down effectively. If n is negative, it will round up effectively. To increase its accuracy, this operation removes anything that comes after the decimal point, cutting the actual number into an integer.

You can get the rounding effect by using ~~ , as above, and the fact that any bitwise operator will force a real number to be an integer. The reason these special operations work is because – 1 when bound to an integer – the value is kept intact.

Remove the last digits – Remove Final Digits
‘Bitwise OR operator’ can also be used to delete the last number of an integer. This means we don’t need to use code like this to switch between types:

Instead, the bitwise OR operator allows us to write:


8. Automatic Binding in Classes

CLASSES

We can use the arrow symbol ES6 in the class method, which will use binding. It will usually save a few lines of code in the class constructor, and we can say hello to repeated expressions like .myMethod = this.myMethod.bind(this) !


9. Truncate 1 Array

ARRAYS

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

For example, if you know the size of the initial array, you can redefine its property length, such as:

This is a special concise solution. However, I have found that the run-time of the slice() method is even faster. If speed is your main goal, consider using these:


10. Get 1 (or more) Items in 1 Array

ARRAY

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


11. Format JSON code

JSON

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

The stringify() method takes two optional parameters: a function replacer , which you can use to filter the displayed JSON, and a space value.

This space value takes an integer that represents the number of spaces – the space you want or a string (such as 't' to insert tabs), and makes it much easier to read the JSON data fetched.


Epilogue

Hope you find these tips useful and find the right way to apply them to your project.

If you have any tips of your own, don’t forget to share them!


Tech Talk via Medium

Share the news now

Source : Techtalk