Home  >  Article  >  Web Front-end  >  Summary and sharing of 20 JavaScript abbreviation techniques to improve efficiency

Summary and sharing of 20 JavaScript abbreviation techniques to improve efficiency

WBOY
WBOYforward
2022-01-13 18:11:201179browse

This article compiles and shares 20 JavaScript abbreviation techniques to improve efficiency. I hope it will be helpful to everyone.

Summary and sharing of 20 JavaScript abbreviation techniques to improve efficiency

Abbreviation tips

When multiple variables are declared at the same time, they can be abbreviated into one line

//Longhand
let x;
let y = 20;
 
//Shorthand
let x, y = 20;

Use destructuring to assign values ​​to multiple variables at the same time

//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];

Smartly use the ternary operator to simplify if else

//Longhand 
let marks = 26; 
let result; 
if (marks >= 30) {
   result = 'Pass'; 
} else { 
   result = 'Fail'; 
} 
//Shorthand 
let result = marks >= 30 ? 'Pass' : 'Fail';

Use the || operator to assign default values ​​to variables

The essence is to take advantage of the characteristics of the || operator. When the result of the previous expression is converted into a Boolean value of false, the value is the result of the following expression.

//Longhand
let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';

Use the && operator to simplify if Statement

For example, a function is called only when a certain condition is true, which can be abbreviated as

//Longhand
if (isLoggedin) {
    goToHomepage();
 }
//Shorthand
isLoggedin && goToHomepage();

Use destructuring to exchange the values ​​of two variables

let x = 'Hello', y = 55;
//Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];

Use arrow functions to simplify functions

//Longhand
function add(num1, num2) {
  return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;

You need to pay attention to the difference between arrow functions and ordinary functions

Use string templates to simplify code

Use template strings instead of original string concatenation

//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);

Multi-line strings can also be simplified using string templates

//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' + 
            'programming language that conforms to the \n' + 
            'ECMAScript specification. JavaScript is high-level,\n' + 
            'often just-in-time compiled, and multi-paradigm.'
            );
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
            programming language that conforms to the
            ECMAScript specification. JavaScript is high-level,
            often just-in-time compiled, and multi-paradigm.`
            );

For multi-value matching, all values ​​can be placed in an array and abbreviated through the array method

//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
  // Execute some code
}
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
   // Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // Execute some code 
}

Smart use of ES6 objects Concise syntax

For example, when the attribute name and variable name are the same, they can be directly abbreviated to one

let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};

Use unary operators to simplify string conversion to numbers

//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';

Use repeat() Method simplifies repeating a string

//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
  str += &#39;Hello &#39;;
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
&#39;Hello &#39;.repeat(5);
// 想跟你说100声抱歉!
&#39;sorry\n&#39;.repeat(100);

Use double asterisks instead of Math.pow()

//Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64

Use double tilde operator (~~) instead of Math.floor()

//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6

It should be noted that ~~ is only applicable to numbers less than 2147483647

Use the expansion operator (...) to simplify the code

Simplify array merging

let arr1 = [20, 30];
//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]

Single layer Copy of object

let obj = {x: 20, y: {z: 30}};
//Longhand
const makeDeepClone = (obj) => {
  let newObject = {};
  Object.keys(obj).map(key => {
      if(typeof obj[key] === &#39;object&#39;){
          newObject[key] = makeDeepClone(obj[key]);
      } else {
          newObject[key] = obj[key];
      }
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: &#39;hello&#39;};
const cloneObj = {...obj};

Find the maximum and minimum values ​​in the array

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

Use for in and for of to simplify the ordinary for loop

let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
  console.log(val);
}
//for in loop
for (const index in arr) {
  console.log(arr[index]);
}

Simplify getting a certain value in the string characters

let str = &#39;jscurious.com&#39;;
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c

Remove object attributes

let obj = {x: 45, y: 72, z: 68, p: 98};
// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}
// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}

Use arr.filter(Boolean) to filter out the value of array members falsey

let arr = [12, null, 0, &#39;xyz&#39;, null, -25, NaN, &#39;&#39;, undefined, 0.5, false];
//Longhand
let filterArray = arr.filter(function(value) {
    if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]
// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]

[Related recommendations: javascript learning Tutorial

The above is the detailed content of Summary and sharing of 20 JavaScript abbreviation techniques to improve efficiency. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete
Previous article:What is the core of ajaxNext article:What is the core of ajax