JavaScript Tips to Improve Your Code Skills

  • 2021-11-14 04:55:33
  • OfStack

Directory 1, filter only 1 value 2, short circuit evaluation (Short-Circuit Evaluation) 2.1 scenario example 3, convert Boolean type 4, convert String type 5, convert Number type 6, quickly seek power 7, quickly convert Float to Integer7.1 use scenario 8, automatically bind in class 9, intercept array 10, get the last element in array 11, format JSON code

Today, I will share with you 11 JavaScript tips that are not often mentioned in daily tutorials. They often appear in our daily work, but they are easily overlooked.

1. Filter only 1 value

The Set type was added in ES 6 and is similar to an array, but the members have only 1 values and no duplicate values. Combined with the extension operator (...), we can create a new array to filter the duplicate values of the original array.


const array = [1, 2, 3, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray); // [1, 2, 3, 5]

Before ES6, we needed a lot more processing code if we wanted to implement this function. This technique applies to the types of values in the array: undefined, null, boolean, string, number. It is not applicable when object, function and array are included.

2. Short circuit evaluation (Short-Circuit Evaluation)

The 3-item operator is a very convenient and quick way to write some simple logical statements


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

However, sometimes when the logic is complicated, the readability of 3-item operators will be difficult to write. At this time, we can use logic and ( & & ) and the logical or () operator to overwrite our expression.

The logical AND and logical OR operators always evaluate their do operands first, and solve their right operands only if the result of the logical expression cannot be determined by the value of the left operand alone.

This is called "short circuit evaluation (Short-ES50Evaluation)" and how it works ( & & ) Operator will return the first false/'falsy'. When all operands are true, the result of the last 1 expression will be returned.


let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3


console.log(0 && null); // Result: 0

The or () operator returns the first value of true/'truthy'. When all operands are false, the result of the last expression is returned.


let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1

console.log(0 || null); // Result: null

2.1 Examples of Scenarios

When we request data from the server, we use the data in another location, but the state of obtaining the data is unknown, such as when we access the data property of this. state.

According to the conventional way, we will first judge the effectiveness of this this. state. data, and then distinguish them according to the effectiveness.


if (this.state.data) {
  return this.state.data;
} else {
  return 'Fetching Data';
}

But we can shorten this logical processing in the above way.


return (this.state.data || 'Fetching Data');

By comparison, it is found that this method is more concise and convenient.

3. Convert Boolean type

Conventional boolean values are only true and false, but in JavaScript we can think of other values as' truthy 'or' falsy '.

With the exception of 0, "", null, undefined, NaN, and false, all of them can be considered 'truthy'. We can convert the variables of series 1 to 'boolean' by using the negative operator!.


const isTrue  = !0;
const isFalse = !1;
const alsoFalse = !!0;
console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"

4. Convert String type

We can convert a variable of type number to type string by using the + join operator.


const val = 1 + "";

console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

5. Convert Number type

Corresponding to the above, we can turn a variable of type string back to that of type number through the addition operator +.


let int = "15";
int = +int;

console.log(int); // Result: 15
console.log(typeof int); Result: "number"

In some contexts, + will be interpreted as a join operator, not an addition operator. When this happens (you want to return an integer instead of a floating-point number), you can use two wavy signs: ~ ~.

(Note that it is in English format) A wavy sign ~ is called "bitwise no operator", which is equivalent to-n-1. So ~ 15 =-16. Using two ~ ~ can effectively negate the operation. This is because-(-n-1)-1 = n + 1-1 = n. Which means ~-16 = 15


const int = ~~"15"

console.log(int); // Result: 15
console.log(typeof int); Result: "number"

6. Quick power finding

Starting with ES7, we can use the power operator * * as a shorthand for exponentiation, which is faster than the previous Math. pow (2, 3). This is a very simple and practical point, but most tutorials don't specifically introduce it.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
0

This should not be confused with the ^ symbol, which is usually used to denote exponents, but in JavaScript is the bit XOR operator. Prior to ES7, the abbreviation of power relied mainly on the bit-left shift operator < < The difference between several writing methods.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
1

It should be noted that 2 < < 3 = 16 is equivalent to 2 ** 4 = 16

7. Fast Float to Integer

Usually we can use Math. floor (), Math. ceil (), and Math. round () to convert float type to integer type. But there is a faster way to truncate floating-point numbers to integers using (bits or operators).


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
2

Depends on whether you're dealing with positive or negative numbers, so it's best to use this shortcut only in certain cases. If n is a positive number, n 0 is effectively rounded down. If n is negative, it is effectively rounded up.

More precisely, the result of this operation is to directly delete the contents after the decimal point and truncate the floating-point number into integers, which is different from the other methods mentioned above.

You can also use ~ ~ to get the same rounding effect, as mentioned above, virtually any bitwise operator forces floating-point numbers to be integers. These special operations are effective because once 1 is forced to be an integer, the value remains unchanged.

7.1 Usage Scenarios

Bits or operators can be used to delete any number of numbers from the end of an integer. This means that we don't have to use such code to convert between types.


let str = "1553"; 
Number(str.substring(0, str.length - 1));


Instead, we can implement our functions in the following ways


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
4

8. Automatic binding in classes

We can implement the invisible binding scope in the class by using the arrow function added by ES 6. As we did before, we need to explicitly bind the method we wrote, similar to this. myMethod = this. myMethod. bind (this). When there are many methods in our class, there will be a lot of binding code writing. Now we can simplify this process by using the arrow function.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
5

9. Truncate an array

If you want to delete values from the end of an array, there are faster alternatives than using splice (). For example, if you know the length of the original array, you can intercept it by redefining its length property.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
6

This is a particularly concise solution. However, the slice () method runs faster. If speed is your main goal, consider using the following methods.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
7

10. Get the last element in the array

The array method slice () can accept negative integers, and if provided, it will truncate the value from the end of the array instead of the beginning.


let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

11. Formatting the JSON code

We may use JSON. stringify in many cases when dealing with JSON, but are you aware that it can help indent JSON? The stringify () method takes two optional parameters: an replacer function, which can be used to filter the displayed JSON, and an space value. The space value accepts an integer indicating the number of spaces required or a string (such as' t 'to insert tabs), which makes it much easier to read the fetched JSON data.


x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
9

Related articles: