Life as a developer is always about learning new things. As front-end developers we must know a few tricks to make our code more elegant and easier to work with.

Maybe you’ve been developing JavaScript for a long time, but sometimes you’re not using the latest features that can fix a problem without fixing it or writing some extra code. These techniques can help you write clean and optimized JavaScript code.

1. Multiple condition judgment

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

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

2. The ternary operator

When we use only a few pairs of if/ ESLE condition judgments, we can simply use the ternary operator.

If there are multiple if/else conditions, it is not recommended

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

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

3. Variable declaration

We use this shorthand when we want to declare two variables that have a common value or a common type

// long
let var1
let var2 = 1

// short
let var1, var2 = 1
Copy the code

4. Null/undefined check and assign defaults

When we need to create a new variable, we sometimes need to check whether the variable referenced for its value is null or undefined. Consider the following implementation:

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

5. Assign values to multiple variables

This is 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];
Copy the code

6. Shorthand for the assignment operator

We deal with a lot of arithmetic operators in our 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;
Copy the code

7. Truth judgment

// long
if (test1 === true)

// short
if (test1)
Copy the code

8. Multi-conditional and/or operations

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

//short 
test1 && callMethod();
Copy the code

9. forEath

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

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

10. Compare the 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'); }Copy the code

11. Arrow function

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

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)();
Copy the code

13. switch

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

// 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]();
Copy the code

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
Copy the code

15. The parameters must be 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! ')}Copy the code

16. Extend operators

//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]Copy the code

For cloning, we can also use extended operators

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

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

17. Template string

If you’re tired of using + to concatenate multiple variables in a single string, consider this approach

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

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

18. Object attribute assignment

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

//short 
let obj = {test1, test2};
Copy the code

19. Convert strings to numbers

//Long let test1 = parseInt('123'); Let test2 = parseFloat (' 12.3 '); //Short let test1 = +'123'; Let test2 = + '12.3';Copy the code

20. Array.find

The find method is really useful when we do have an array of objects and we want to look up specific objects based on object properties.

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); 
Copy the code

21. Multi-conditional judgment

Wouldn’t it be better if we had code to check the type, and we needed to call different methods based on the type, and we could use multiple else Ifs or switch?

// 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();Copy the code

22. Index lookup

We do use the indexOf() method when we iterate over an array to find a particular value, but what if we found a better one? Let’s 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 }Copy the code

The bitwise ~ operator returns a true value that is not -1. Taking the inverse is as easy as doing ~. Alternatively, we can use the include() function:

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

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' ]
]

**/
Copy the code

24. Object.values()

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

[ 'abc', 'cde']

**/
Copy the code

25. Repeat a string multiple times

To repeat the same characters over and over again, we could use a for loop and add them to the same loop, but what if we had 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);
Copy the code

26. Find the maximum and minimum values in the array

const arr = [1, 2, 3]; Math. Max (... arr); / / 3 Math. Min (... arr); / / 1Copy the code

This abstract to: www.toutiao.com/i6915617290…