1. Convert to numbers

Using the addition operator + can quickly achieve the opposite effect.

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

This can also be used to convert Boolean values to numbers, as shown below

console.log(+true); // Return: 1
console.log(+false); // Return: 0
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 :~~.

Using two waves in succession effectively negates the operation because — (-n — 1) — 1 = n + 1 — 1 = n. In other words, ~ -16 is 15.

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

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

2. Better performance operations

Starting with ES7, you can use the exponential operator ** as a shorthand for powers, which is faster than writing Math.pow(2, 3). This is simple stuff, but it’s on the list because not many tutorials update this operator.

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

This should not be confused with the ^ symbol commonly used to represent exponents, but in JavaScript it is the bitwise xor operator.

Prior to ES7, abbreviations only existed for powers of base 2, using the bitwise left-shift operator <<

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

For example, 2 << 3 = 16 is equal to 2 ** 4 = 16.

3. Fast conversion from floating point to integer

If you want to convert floating point numbers to integers, you can use math.floor (), math.ceil (), or math.round (). But there’s a faster way to use | (or operators) will float truncated as an integer.

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

| behavior depends on the processing is positive or negative, so best only in certain cases using this shortcut.

If n is positive, then the n | 0 rounding down effectively. If n is negative, it is effectively rounded up. More precisely, this operation deletes anything after the decimal point, truncating the floating point number to an integer.

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

Delete the last number

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

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

Instead, bitwise or operators can be written like this:

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

4. Get the last item in the array

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

5. Use logical operators wisely

And operator (&&)

The operator returns the value of the second operator if the first operator has a Boolean value of true. If the first operator has a Boolean value of false, the value of the first operator is returned directly and the second operator is not evaluated.

if(is){run()} // equivalent to is && run()Copy the code
Or operator (| |)

The or operator returns the value of the first operator if the Boolean value of the first operator is true and does not evaluate the second operator. Returns the value of the second operator if the first operator has a Boolean value of false.

function run(evt){
    var evt=evt||window.event;
}

var num = 1;
true || (num = 2) // true
Copy the code

6. Merge objects

The need to merge multiple objects in JavaScript already exists, especially when we start creating classes and widgets with options:

const person={name:"Tony",gender:"male"};
const attr={skill:"Modelling"}; / / the firstletnewobj=Object.assign({},person,attr); // Second (more simplified)letsummary = {... person, ... attr};Copy the code

7. Array deduplication

This is easy to implement using ES6’s new data structures.

Var j = [...new Set([1, 2, 3])]Copy the code

For details about the ES6 syntax, see the ES6 documentation

8. Optimize your Switch statements

Before optimization:

const dogSwitch=(branch)=>{
    switch(branch){
        case "develop":
            return "http://develop.com"
            break
        case "test":
            return "http://test.com"
            break
        case "uat":
            return "http://uat.com"
            break
        case "prd":
            return "http://prd.com"
            break
        default:
            return "http://prd.com"
    }
}
dogSwitch("uat")
Copy the code

After the optimization:

const dogSwitch = (branch) =>({
  "develop": "http://develop.com"."test": "http://test.com"."uat": "http://uat.com"."prd": "http://prd.com"
})[branch]||"http://prd.com";
dogSwitch("uat")
Copy the code

Thank you for reading

Lots of guidance.

If you like it, please bookmark it or star it, or give my Github a star~~

github.com/liyan0411