26 JavaScript optimization techniques

The life of a developer is always learning new things. As a front-end developer, we must know some techniques to make our code more elegant and work easier.

Maybe you have been doing JavaScript development for a long time, but sometimes you may not use the latest features that can solve the problem without the need to solve or write some additional code. These techniques can help you write clean and optimized JavaScript code.

1. Multiple condition judgments

// long
if( x === 'a' || x === 'b' || x === 'c' || x === 'd'){
  // logic
}

// short
if(['a', 'b', 'c', 'd'].includes(x)){
  // logic
}

2. Ternary Operator

When we only use some if/esle conditional judgments, we can simply use ternary operators to achieve.

If there are many pairs of if/else condition judgments, it is not recommended to use

// long
let flag
if(x > 10){
  flag = true
}else {
  flag = false
}

// short
let flag = x > 10 ? true : false

3. Variable declaration

When we want to declare two variables that have a common value or a common type, this shorthand form can be used

// long
let var1
let var2 = 1

// short
let var1, var2 = 1

4. Empty/undefined check and assign default value

When we need to create a new variable, sometimes we need to check whether the variable referenced by its value is null or undefined, we can consider the following implementation:

// long
if(test1 !== null || test1 !== undefined || test1 !== ""){
  let test2 = test1;
}else {
  let test2 = ''
}

// short
let test2 = test1 || ''

5. Assign values ​​to multiple variables

This method is very useful when we are dealing with multiple variables and want to assign different values ​​to different variables.

//long 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;

//Short 
let [test1, test2, test3] = [1, 2, 3];

6. Shorthand for assignment operator

We deal with many arithmetic operators in programming. This is one of the useful techniques for assigning operators to JavaScript variables

// long
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;

// short
test1++;
test2--;
test3 *= 20;

7. Truth judgment

// long
if (test1 === true)

// short
if (test1)

8. Multi-condition AND/OR operation

//long 
if (test1) {
 callMethod(); 
} 

//short 
test1 && callMethod();

9. forEath

// long
for (var i = 0; i < testList.length; i++)

// short
testList.forEach(item => console.log(item))

10. Compare return values

// long
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);
}

// short
function checkReturn() {
    return test || callMe('test');
}

11. Arrow functions

//long 
function add(a, b) { 
   return a + b; 
} 
//short 
const add = (a, b) => a + b;

12. Short function calls

// long
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// short
(test3 === 1? test1:test2)();

13. switch

We can save the condition in the key-value object and use it according to the condition.

// long
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}

// short
var data = {
  1: test1,
  2: test2,
  3: test
};

data[something] && data[something]();

14. Default parameters

//long
function add(test1, test2) {
  if (test1 === undefined)
    test1 = 1;
  if (test2 === undefined)
    test2 = 2;
  return test1 + test2;
}

//short
add = (test1 = 1, test2 = 2) => (test1 + test2);
add() //output: 3

15. Parameter must be passed and verified

// long
function hello(obj){
  let {name, age} = obj
  if(!name){
    console.warn('name is null, pls check!')
    return ''
  }
  if(!age){
    console.warn('age is null, pls check!')
    return ''
  }
  return `${name}: ${age}`
}

// short
function hello(obj){
  let {name = required('name'), age = required('age')} = obj
  return `${name}: ${age}`
}

function required(key){
  console.warn(`${key} is null, pls check!')
}

16. Spread Operator

//long
const data = [1, 2, 3];
const test = [4 ,5 , 6].concat(data);

//short
const data = [1, 2, 3];
const test = [4 ,5 , 6, ...data];
console.log(test); // [ 4, 5, 6, 1, 2, 3]

For cloning, we can also use the spread operator

//long
const test1 = [1, 2, 3];
const test2 = test1.slice()

//short
const test1 = [1, 2, 3];
const test2 = [...test1];

17. Template String

If you are tired of using + in a single string to connect multiple variables, you can consider this way

//long
const welcome = 'Hi ' + user + ' ' + name + '.'

//short
const welcome = `Hi ${user} ${name}`;

18. Object attribute assignment

let test1 = 'a'; 
let test2 = 'b';
//Long
let obj = {test1: test1, test2: test2}; 

//short 
let obj = {test1, test2};

19. Convert string to number

//Long
let test1 = parseInt('123'); 
let test2 = parseFloat('12.3'); 

//Short
let test1 = +'123'; 
let test2 = +'12.3';

20. Array.find

When we do have an array of objects and we want to find specific objects based on object properties, the find method is really useful.

const data = [{
        type: 'test1',
        name: 'abc'
    },
    {
        type: 'test2',
        name: 'cde'
    },
    {
        type: 'test1',
        name: 'fgh'
    },
]
// long
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); 

21. Multi-condition judgment

If we have code to check the type, and need to call different methods based on the type, we can choose to use multiple else if or switch, is there a better one?

// long
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);
}

// short
const types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};

let func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();

22. Index Search

When we iterate the array to find a specific value, we do use indexOf()methods, what if we find a better method? Let us look at this example.

//long
if(arr.indexOf(item) > -1) { // item found 
}
if(arr.indexOf(item) === -1) { // item not found
}

//short
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}

The ~bitwise operator will return a real value other than -1. Reversing is ~as simple as doing it. In addition, we can also use include()functions:

if (arr.includes(item)) { 
// true if the item found
}

24. Object.entries()

This feature helps to convert an object into an array of objects

const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** ouput

[ [ 'test1', 'abc' ],
  [ 'test2', 'cde' ],
  [ 'test3', 'efg' ]
]

**/

24. Object.values()

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

[ 'abc', 'cde']

**/

25. Repeat a string multiple times

To repeat the same characters again and again, we can use a for loop and add them to the same loop, but what if we have a shorthand method?

//long 
let test = ''; 
for(let i = 0; i < 5; i ++) { 
  test += 'test '; 
} 
console.log(str); // test test test test test 

//short 
'test '.repeat(5);

26. Find the maximum and minimum values ​​in an array

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

This article is excerpted : www.toutiao.com/i6915617290...

Guess you like

Origin blog.csdn.net/hugo233/article/details/112758064