Unmissable JS code optimization skills (continuously updated)

1. If statement with multiple conditions

Put multiple values ​​in an array, then call the array's includes method.

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
复制代码

2. Simplify if true...else

For if-else conditions that do not contain large logic, the following shortcuts can be used. We can achieve this simplification by simply using the ternary operator.

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//或者我们也可以直接用
let test = x > 10;
console.log(test);
复制代码

This can be done if there are nested conditions.

let x = 300,
test2 = (x > 100) ? 'greater than 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
复制代码

3. Declare variables

This shorthand can be used when we want to declare two variables with the same value or the same type.

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;
复制代码

4. null, undefined and null value checking

When we create new variables, sometimes we want to check if the referenced variable is not null or undefined. JavaScript does have a nice shortcut for implementing this kind of check.

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';
复制代码

5. null checking and default assignment

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // 输出 ""
复制代码

6. undefined checking and default assignment

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // 输出 ""
复制代码

General value check

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // 输出: 'test'
复制代码

In addition, for the above points 4, 5, and 6, the ?? operator can be used.

If the value on the left is null or undefined, the value on the right is returned. By default, it will return the value on the left.

const test= null ?? 'default';
console.log(test);
// 输出结果: "default"
const test1 = 0 ?? 2;
console.log(test1);
// 输出结果: 0
复制代码

7. Assign values ​​to multiple variables

This trick is very useful when we want to assign values ​​to multiple different variables.

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];
复制代码

8. Simple assignment operator

During programming, we deal with a large number of arithmetic operators. This is one of the useful tricks of JavaScript variable assignment operators.

// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2--;
test3 *= 20;
复制代码

9. if to determine whether the value exists

It's a common handy trick we all use, and it's still worth mentioning here.

// Longhand
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand //检查空字符串、null或者undefined
if (test1)
复制代码

Note: If test1 has a value, the logic after the if will be executed. This operator is mainly used for null or undefined checks.

10. The && operator for multiple conditions

To call a function only when the variable is true, use the && operator.

//Longhand 
if (test1) {
 callMethod(); 
} 
//Shorthand 
test1 && callMethod();
复制代码

11. for each loop

This is a common loop simplification trick.

// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)
复制代码

Iterate over each variable of the array.

function testData(element, index, array) {
  console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// logs: test[0] = 11, test[1] = 24, test[2] = 32
复制代码

12. Return after comparison

We can also use comparisons in the return statement, which reduces 5 lines of code to 1.

// Longhand
let test;
function checkReturn() {
    if (!(test === undefined)) {
        return test;
    } else {
        return callMe('test');
    }
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
    console.log(val);
}
// Shorthand
function checkReturn() {
    return test || callMe('test');
}
复制代码

13. Arrow functions

//Longhand 
function add(a, b) { 
   return a + b; 
} 
//Shorthand 
const add = (a, b) => a + b;
复制代码

More examples:

function callMe(name) {
  console.log('Hello', name);
}
callMe = name => console.log('Hello', name);
复制代码

14. Short function calls

We can use the ternary operator to implement multiple function calls.

// Longhand
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}
// Shorthand
(test3 === 1? test1:test2)();
复制代码

15. switch simplification

We can store conditions in key-value objects and call them based on the conditions.

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();
复制代码

16. 隐式返回

通过使用箭头函数,我们可以直接返回值,不需要 return 语句。

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)
复制代码

17. 指数表示法

// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) {
复制代码

18. 默认参数值

//Longhand
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}
//shorthand
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //输出结果: 3
复制代码

19. 延展操作符简化

//longhand
// 使用concat连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);
//shorthand
// 连接数组
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]
复制代码

我们也可以使用延展操作符进行克隆。

//longhand
// 克隆数组
const test1 = [1, 2, 3];
const test2 = test1.slice()
//shorthand
//克隆数组
const test1 = [1, 2, 3];
const test2 = [...test1];
复制代码

20. 模板字面量

如果你厌倦了使用 + 将多个变量连接成一个字符串,那么这个简化技巧将让你不再头痛。

//longhand
const welcome = 'Hi ' + test1 + ' ' + test2 + '.'
//shorthand
const welcome = `Hi ${test1} ${test2}`;
复制代码

21. 跨行字符串

当我们在代码中处理跨行字符串时,可以这样做。

//longhand
const data = 'abc abc abc abc abc abc\n\t'
    + 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
         test test,test test test test`
复制代码

22. 对象属性赋值

let test1 = 'a'; 
let test2 = 'b';
//Longhand 
let obj = {test1: test1, test2: test2}; 
//Shorthand 
let obj = {test1, test2};
复制代码

23. 将字符串转成数字

//Longhand 
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 
//Shorthand 
let test1 = +'123'; 
let test2 = +'12.3';
复制代码

24. 解构赋值

//longhand
const test1 = this.data.test1;
const test2 = this.data.test2;
const test2 = this.data.test3;
//shorthand
const { test1, test2, test3 } = this.data;
复制代码

25. 数组 find 简化

当我们有一个对象数组,并想根据对象属性找到特定对象,find 方法会非常有用。

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        name: 'fgh'
    },
]
function findtest1(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'test1' && data[i].name === name) {
            return data[i];
        }
    }
}
//Shorthand
filteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');
console.log(filteredData); // { type: 'test1', name: 'fgh' }
复制代码

26. 条件查找简化

如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?

// Longhand
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
复制代码

27. indexOf 的按位操作简化

在查找数组的某个值时,我们可以使用 indexOf() 方法。但有一种更好的方法,让我们来看一下这个例子。

//longhand
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}
//shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}
复制代码

按位 ( ~ ) 运算符将返回 true(-1 除外),反向操作只需要!~。另外,也可以使用 include() 函数。

if (arr.includes(item)) { 
// 如果找到项目,则为true
}
复制代码

28. Object.entries()

这个方法可以将对象转换为对象数组。

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]
**/
复制代码

29. Object.values()

这也是 ES8 中引入的一个新特性,它的功能类似于 Object.entries(),只是没有键。

const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
复制代码

30. 双重按位操作

// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
复制代码

31. 重复字符串多次

为了重复操作相同的字符,我们可以使用 for 循环,但其实还有一种简便的方法。

//longhand 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 
//shorthand 
'test '.repeat(5);
复制代码

32. 查找数组的最大值和最小值

const arr = [1, 2, 3]; 
Math.max(…arr); // 3
Math.min(…arr); // 1
复制代码

33. 获取字符串的字符

let str = 'abc';
//Longhand 
str.charAt(2); // c
//Shorthand 
str[2]; // c
复制代码

34. 指数幂简化

//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
复制代码

————————————————————————————

以后遇到了再进行补充~~~~

Guess you like

Origin juejin.im/post/7078575191244144670