Preface: Recently I read some articles on simplifying JS code. I think one of them is pretty good, but it is in English. I also read some Chinese translations. One of them is that the word-by-word translation is too stiff and does not become my own. The other is that the author has added new content but has not updated it in time. So I translated it into this article according to my own language. The characteristics of this article are mainly concise and concise. When declaring multiple variables at the same time, you can shorten it to one line://Longhand let x; let y = 20; //Shorthand let x, y = 20; Destructuring can be used 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]; Using 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 use the characteristics of the || operator. When the result of the previous expression is converted to a Boolean value of //Longhand let imagePath; let path = getImagePath(); if (path !== null && path !== undefined && path !== '') { imagePath = path; } else { imagePath = 'default.jpg'; } //Shorthand let imagePath = getImagePath() || 'default.jpg'; Using the && operator to simplify if statementsFor example, if a function is called only when a certain condition is true, it can be shortened to //Longhand if (isLoggedin) { goToHomepage(); } //Shorthand isLoggedin && goToHomepage(); Using destructuring to swap the values of two variableslet x = 'Hello', y = 55; //Longhand const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x]; Apply arrow functions to simplify functions//Longhand function add(num1, num2) { return num1 + num2; } //Shorthand const add = (num1, num2) => num1 + num2; Note the difference between arrow functions and normal functions Simplify your code using string templates Use template strings instead of raw 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 simplified using array methods//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 } Using the concise syntax of ES6 objectsFor example: When the attribute name and variable name are the same, they can be abbreviated to one. let firstname = 'Amitav'; let lastname = 'Mishra'; //Longhand let obj = {firstname: firstname, lastname: lastname}; //Shorthand let obj = {firstname, lastname}; Using unary operators to simplify string to number conversion//Longhand let total = parseInt('453'); let average = parseFloat('42.6'); //Shorthand let total = +'453'; let average = +'42.6'; Use the repeat() method to simplify repeating a string//Longhand let str = ''; for(let i = 0; i < 5; i ++) { str += 'Hello '; } console.log(str); // Hello Hello Hello Hello Hello // Shorthand 'Hello '.repeat(5); // I want to say sorry to you 100 times! 'sorry\n'.repeat(100); Use double asterisks instead of Math.pow()//Longhand const power = Math.pow(4, 3); // 64 // Shorthand const power = 4**3; // 64 Use the double tilde operator (~~) instead of Math.floor()//Longhand const floor = Math.floor(6.8); // 6 // Shorthand const floor = ~~6.8; // 6 Note that ~~ is only applicable to numbers less than 2147483647 Using the spread operator (...) to simplify code Simplifying array merginglet arr1 = [20, 30]; //Longhand let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80] //Shorthand let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80] Copying a single layer objectlet obj = {x: 20, y: {z: 30}}; //Longhand const makeDeepClone = (obj) => { let newObject = {}; Object.keys(obj).map(key => { if(typeof obj[key] === 'object'){ 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: 'hello'}; const cloneObj = {...obj}; Finding the maximum and minimum values in an 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 looplet 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 character in a stringlet str = 'jscurious.com'; //Longhand str.charAt(2); // c //Shorthand str[2]; // c Removing Object Propertieslet 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 falsey of the array memberlet arr = [12, null, 0, 'xyz', null, -25, NaN, '', 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] This concludes this article about 20 JS abbreviation tips to improve work efficiency. For more relevant JS abbreviation tips, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Build a high-availability MySQL cluster with dual VIP
>>: HTML table only displays the outer border of the table
1. Idea It only took 6 seconds to insert 1,000,00...
Preface add_header is a directive defined in the ...
Sometimes some docker containers exit after a per...
Table of contents 1. Ternary operator judgment 2....
1. Download the required packages wget -P /usr/lo...
Html code: Copy code The code is as follows: <t...
Table of contents 1. Virtual Host 1.1 Virtual Hos...
Table of contents 1. router-view 2. router-link 3...
Configure multiple servers in nginx.conf: When pr...
Table of contents 1. Introduction to UDP and Linu...
The difference between := and = = Only when setti...
Table of contents 1. Installation 2. Use Echarts ...
1. Download address: mysql-8.0.17-winx64 Download...
This article mainly introduces the wonderful use ...
How to implement Mysql switching data storage dir...