JavaScript simplification techniques

1. Filter unique values

The Set object type is introduced in ES6. With the expansion operation, we can use it to create a new array with only unique values.

const array = [1, 1, 2, 3, 5, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Result: [1, 2, 3, 5]

Prior to ES6, isolating unique values would involve much more code.
This technique applies to arrays that contain basic types: undefined, null, boolean, string, and number. (if you have an array containing objects, functions or other arrays, you need a different method!)
2. And or operation

Ternary operators are a quick way to write simple (sometimes not so simple) conditional statements, as follows:

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

But sometimes using ternary operators can be complicated. We can use the 'and' operators in a more concise way. This is commonly referred to as "short circuit" or "short circuit".
How does it work

Suppose we only want to return one of two or more options.
Use & & to return a value whose first condition is false. If each operand evaluates to true, the last evaluated expression is returned.

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

Using | returns the value whose first condition is true. If each operand evaluates to false, the last evaluated expression is returned.

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

Example 1

Suppose we want to return the length of a variable, but we don't know the type of variable.
We can use if/else statements to check that foo is an acceptable type, but this can become very verbose. Or running can help us simplify operations:

return (foo || []).length;

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

Have you ever encountered problems accessing nested object properties? You may not know whether an object or one of its child properties exists, which can lead to frustrating errors.
Suppose we want to be in this A property named data is accessed in state, but data is undefined until our program successfully returns an acquisition request.
Depending on where we use it, call this state. Data may prevent our application from running. In order to solve this problem, we can make further judgment:

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

But this seems to be repeated‘ The 'or' operator provides a more concise solution:

return this.state.data || "Fetching Data";
A new feature: Optional Chaining

In the past, in the call of Object property chain, it was easy to cause the error of Cannot read property xxx of undefined later because a property did not exist.
Then optional chaining is added For such an operator, it will first judge the previous value. If it is null or undefined, it will end the call and return undefined.
For example, we can refactor the above example to this state. data?. (). Or, if we mainly focus on whether state is defined, we can return this state?. data.
The proposal is currently in phase 1 as an experimental function. You can read it here. Now you can use your JavaScript through Babel to add @ Babel / plugin proposal optional chaining to your babelrc file.
3. Convert to Boolean

In addition to the regular Boolean values true and false, JavaScript treats all other values as' true 'or' false '.
Unless otherwise defined, all values in JavaScript are 'true', except 0, "", null, undefined, NaN, and of course false, which are 'false'
We can easily switch between true and false by using the negative operator. It also converts the type to "boolean".

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

4. Convert to string

To quickly convert numbers to strings, we can use the concatenation operator + followed by a set of empty quotation marks "".

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

5. Convert to number

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";
This can also be used to convert Boolean values to numbers, as follows:

console.log(+true); // Return: 1
console.log(+false); // Return: 0

In some contexts, + will be interpreted as a join operator rather than an addition operator. When this happens (you want to return an integer instead of a floating-point number), you can use two tilde signs: ~ ~.
The continuous use of two waves effectively negates the operation because - (- n-1) - 1 = n + 1-1 = n. In other words, ~ - 16 equals 15.

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

Although I can't think of many use cases, the bitwise NOT operator can also be used on Boolean values: ~ true = -2 and ~ false = -1.
6. Better performance computing

Starting with ES7, you can use the exponential operator * * as a shorthand for power, which is better than writing math Pow (2, 3) is faster. This is a very simple thing, but it appears in the list because not many tutorials have updated this operator.

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

This should not be confused with the ^ symbol commonly used to represent an index, but in JavaScript it is a bitwise XOR operator.
Prior to ES7, only powers based on 2 were abbreviated, using the bitwise shift left operator<<

Math.pow(2, n);
2 << (n - 1);
2 ** n;
For example, 2 << 3 = 16 Equal to 2 ** 4 = 16. 

7. Fast 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 is a faster way to truncate a floating-point number to an integer using | (bit or operator).

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

|The behavior of depends on whether you are dealing with positive or negative numbers, so it's best to use this shortcut only in certain cases.
If n is positive, then n | 0 is effectively rounded down. If n is negative, it is effectively rounded up. More precisely, this operation will delete anything after the decimal point and truncate the floating-point number to an integer.
You can use ~ ~ to get the same rounding effect. As mentioned above, virtually any bit operator forces a floating-point number to an integer. These special operations are effective because once forced to an integer, the value remains unchanged.
Delete last number

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

let str = "1553";
Number(str.substring(0, str.length - 1));
Instead, bitwise OR operators can be written as follows:
console.log((1553 / 10) | 0); // Result: 155
console.log((1553 / 100) | 0); // Result: 15
console.log((1553 / 1000) | 0); // Result: 1

8. Automatic binding in class

We can use ES6 arrow notation in class methods, and by doing so, we can implicitly bind. This usually saves a few lines of code in our class constructor, and we can happily bid farewell to repeated expressions, such as this myMethod = this. myMethod. bind(this)

import React, { Component } from React;
export default class App extends Compononent {
  constructor(props) {
  super(props);
  this.state = {};
  }
myMethod = () => {
    // This method is bound implicitly!
  }
render() {
    return (
      <>
        <div>
          {this.myMethod()}
        </div>
      </>
    )
  }
};

9. Array truncation

If you want to delete a value from the end of an array, there is a faster method than using splice().
For example, if you know the size of the original array, you can redefine its length attribute, like this

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]

This is a particularly concise solution. However, I found that the slice() method runs faster. If speed is your primary goal, consider using:

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]

10. Gets the last item in the array

The array method slice() can accept negative integers. If it is provided, it will accept the value at the end of the array instead of the value at the beginning of the array.

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 JSON code

Finally, you may have used JSON before Stringify, but do you realize that it can also help you indent JSON?
The stringify() method has two optional parameters: a replacer function that can be used to filter the displayed JSON and a space value.

console.log(JSON.stringify({ alpha: "A", beta: "B" }, null, "\t"));
// Result:
// '{
//     "alpha": A,
//     "beta": B
// }'

Posted by Mardoxx on Wed, 18 May 2022 09:06:43 +0300