This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

1. Filter unique values

The Set type, which is similar to an array but has unique member values, is new to ES6. Combined with extension operators (…) We can create a new array to filter out 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]
Copy the code

Prior to ES6, we needed a lot more processing code to implement this functionality. This technique applies only when the values in an array are of type: undefined, NULL, Boolean, string, number. Not applicable when object, function, or array is included.

2, short circuit evaluation

The ternary operator is a quick and convenient way to write simple logical statements

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

But sometimes when the logic is complicated, the ternary operators can be hard to read to write. This time, we can use logic and (&) and the logic or (| |) operator to rewrite our expression.

The logic and and or operators always evaluate their operands first, and evaluate their right-hand operands only if the result of the logical expression cannot be determined by the value of the left-hand operand alone. This is called short-circuit Evaluation.

The and (&&) operator will return the first false/ ‘falsy’ value. When all operands are true, the result of the last expression is returned.

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3
console.log(0 && null); // Result: 0
Copy the code

Or (| |) operator returns the first true/’ truthy value. 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
Copy the code

Scenario, for example,

When we request data from the server, we use the data in another location, but the state of the retrieved data is not known, such as when we access the data property of this.state. According to the conventional way, we will judge the validity of this.state.data first, and then discriminate according to the validity.

if (this.state.data) {
    return this.state.data;
} else {
    return 'Fetching Data';
}
// But we can abbreviate this logic by the way above.
return (this.state.data || 'Fetching Data');
// This method is much simpler and more convenient.
Copy the code

3, convert Boolean

Normal 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, everything else can be considered ‘truthy’.

We can use the negative operator! Convert a list of variables to Boolean.

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

4. Convert to String

We can convert a variable of type number to a string using the + concatenation operator

const val = 1 + "";
console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"
Copy the code

5. Convert Number

Alternatively, we can convert a string variable back to number using the addition operator +

let int = "15";
int = +int;
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Copy the code

In some contexts, + will be interpreted as the join operator, not the addition operator. When this happens (you want to return an integer, not a floating-point number), you can use two tilde: ~~. A tilde ~, called the bitwise unoperator, is equivalent to -n-1. So minus 15 is minus 16.

Two negation operations are valid using ~ ~. That’s because minus n minus 1 minus 1 is n plus 1 minus 1 is n. So minus 16 is equal to 15

const int = ~~"15"
console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Copy the code

6. Quick exponentiation

Starting with ES7, we can use the exponentiation operator ** as a shorthand for exponentiation, which is faster than math.pow (2, 3) before.

console.log(2 ** 3); // Result: 8
Copy the code

This should not be confused with the ^ symbol, which is usually used to represent exponents, but is the bitxor operator in JavaScript. Prior to ES7, the shorthand for powers relied mainly on the bit-left shift operator <<

Math.pow(2, n);
2 << (n - 1);
2**n;
Copy the code

Note that 2 << 3 = 16 is equivalent to 2 ** 4 = 16

7, fast Float to Integer

We can normally convert float to integer using math.floor (), math.ceil (), and math.round ().

But there’s a faster way to use | (or operators) will float truncated as an integer.

console.log(23.9 | 0);  // Result: 23
console.log(-23.9 | 0); // Result: -23
Copy the code

Your behavior depends on whether you’re dealing with positive or negative numbers, so it’s best to use this shortcut only when certain.

If n is a positive number, n | 0 rounding down effectively. If n is negative, it effectively rounds up. To be more precise, the result of this operation is to simply delete the content after the decimal point and truncate the floating point number to an integer, 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 a floating point number to be an integer. These special operations work because once an integer is forced, the value remains the same.

Usage scenarios

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

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

Instead, we can implement our functionality in the following ways

console.log(1553 / 10   | 0// Result: 155
console.log(1553 / 100  | 0// Result: 15
console.log(1553 / 1000 | 0// Result: 1
Copy the code

8. Automatic binding in classes

We can implement invisible binding scopes in our classes by using the arrow functions added to ES6. Following the previous treatment, we need to explicitly bind the method we wrote, like this.mymethod = this.mymethod.bind (this). When we have a lot of methods in our class, we add a lot of binding code. Now we can simplify this process by using arrow functions.

import React, { Component } from React;
export default class App extends Compononent {
    constructor(props) {
        super(props);
        this.state = {};
    }
    myMethod = () = > {
        // Implicit binding
    }
    render() {
        return (
            <>
            <div>
            {this.myMethod()}
            </div>
            </>)}};Copy the code

9. Intercept an array

If you want to remove 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 attribute.

let array = [0.1.2.3.4.5.6.7.8.9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]
Copy the code

This is a particularly neat solution. However, the slice() method is faster to run.

let array = [0.1.2.3.4.5.6.7.8.9];
array = array.slice(0.4);
console.log(array); // Result: [0, 1, 2, 3]
Copy the code

Get the last element of the array

The array method slice() can accept negative integers and, if provided, will truncate values from the end of the array, not 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]
Copy the code