Some useful JavaScript tips

Tram Ho

In the process of learning and working, I have made a list of some of the time-saving tips that I find in members, code on websites and anywhere else I’m using now. In this article, I would like to share some manual tips that have been helping me especially smart or helpful. This post is intended to be helpful for beginners, but I hope even those who have worked for a long time will find something new on this list.

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

1. Filter for 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.

Before ES6, isolating unique values ​​would involve more code than that! 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! Use filters for example.

Below, there are some ways to filter, get unique values.

2. Evaluation of short circuit

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

How does it work with Javascript?

Let’s say we want to return only one or two options. Using && will return the first false value. If all the evaluated operands are true, the last evaluated expression will be returned.

Use | | will return the first true value or true. If all the operands evaluate to false, the last 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 the if / else statement to check if foo is an acceptable type, but this can be quite long. The short-circuit rating allows us to do this instead:

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

Example 2 Have you ever had trouble 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.

And now we want to access an attribute called data in this.state, but the data is not defined until our program returns the fetch request successfully. Depending on where we use it, calling this.state.data may prevent our application from running. To solve this problem, we can package it in one condition:

But that seems quite repetitive. Operator or provide a more concise solution:

A new proposed feature: Optional strings

There is currently a proposal to allow the optional string when trying to return an asset deep in a tree-like structure. As suggested, the question mark icon ? can only be used to extract an attribute if it is not null.

For example: We can refactor our example above into this.state.data?. (), Therefore only return data if it is not null. Or, if we are primarily concerned with whether the state is specified, we can return this.state? .Data

The proposal is currently in Phase 1, as an experimental feature. You can read about it here and now you can use your JavaScript through Babel, by adding @ babel / plugin-suggestions-options-strings to your .babelrc file.

3. Convert to Boolean

Besides the usual boolean values ​​that are true and false, JavaScript also treats all other values ​​as truey or referenced falsy.

Unless otherwise specified, all values ​​in JavaScript are ‘truey, except for 0, “”, null, undefined, NaN and of course false, that is fals falsy.

We can easily convert 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, although the only reason you choose to define it wrong is! 1 is if you are playing code!

4. Convert to String

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

5. Convert to numbers

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

This can also be used to convert booleans into numbers, 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 the bitwise NOT operator, is the operator equivalent to -n – 1. So, for example, ~ 15 equals -16. Using two tildes in a row eliminates the effect, because – (- n – 1) – 1 = n + 1 – 1 = n. In other words, ~ – 16 equals 15.

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

6. Fast powers

Since ES7, exponential operators ** can be used as a shorthand for powers, faster than writing Math.pow (2, 3). This is a simple tool, but it makes the list because not many instructions have been updated to include this operator!

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

Before ES7, shorthand only existed for powers with base 2, using the left bit shift operator <<: The following expressions are equivalent:

2 << 3 = 16 is equivalent to 2 ** 4 = 16.

7. Quickly float to integer

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

Behavior of | varies depending on whether you handle positive or negative numbers, so it’s best to use this shortcut only if you’re sure.

If n is positive, n | 0 round effect down. If n is negative, it effectively rounds. 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 stays the same.

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 we don’t have to use code like this to convert between types:

Instead, the bitwise OR operator allows us to write:

8. Close the book automatically in the classroom

We can use ES6 arrow notation in class methods and in that way, constraints are implied. This will usually save a few lines of code in our class builder and we can happily say goodbye to repeated expressions like this.myMethod = this.myMethod.bind (this)

9. Cut an array

If you want to get rid of 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, I have found the run time of the slice () method even faster. If speed is your main goal, consider using something like this:

10. Get the last item (s) in an array

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

11. Format JSON code

Finally, you may have used JSON.opesify before, but have you realized that it can also help you indent JSON as well?

The stringify () method 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 it much easier to read the fetched JSON data.

Overall, I hope you find these tips as useful as I did when I first discovered them.

My writing here is the end. Hope it will be of some help to you guys. The article is also difficult to avoid mistakes, hope everyone is sympathetic, and look forward to the comments of everyone for the article to be more complete.

Share the news now

Source : Viblo