preface
Recently saw some simplified JS code, one feels good, but is in English, also saw some Chinese translation, is a literal translation is too hard and not become their own things, another is behind the author doesn’t have a new update, so I translated into this article according to their own language, in this paper, characteristic with concise give priority to
20 JavaScript Techniques that Will Save Your Time
The body of the
Shorthand skills
When multiple variables are declared at the same time, it can be shortened to a single line
//Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;
Copy the code
With deconstruction, multiple variables can be assigned simultaneously
//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5.8.12];
Copy the code
Clever ternary operators 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';
Copy the code
Using the | | operator to variable specifies the default values
Essence is the use of the | | operator, the characteristics of the current expression of the results when they are converted to Boolean value of false value as 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';
Copy the code
Simplify if statements with && operators
For example, a function is called only if a condition is true
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
Copy the code
Use deconstruction 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];
Copy the code
Apply the arrow function to simplify the function
//Longhand
function add(num1, num2) {
return num1 + num2;
}
//Shorthand
const add = (num1, num2) = > num1 + num2;
Copy the code
Note the difference between arrow functions and normal functions
Simplify code with string templates
Use template strings instead of the 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}`);
Copy the code
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.`
);
Copy the code
For multi-value matching, you can put all values in an array, shorthand by 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
}
Copy the code
Use the concise syntax of ES6 objects
For example, when an attribute name and a variable name are the same, they can be shortened to one
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
Copy the code
Use 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';
Copy the code
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 100 sorry to you!
'sorry\n'.repeat(100);
Copy the code
Use double stars instead of math.pow ()
//Longhand
const power = Math.pow(4.3); / / 64
// Shorthand
const power = 4**3; / / 64
Copy the code
Use the double tilde operator (~~) instead of math.floor ()
//Longhand
const floor = Math.floor(6.8); / / 6
// Shorthand
const floor = ~~6.8; / / 6
Copy the code
Note that ~~ only applies to numbers less than 2,147,483,647
Ingenious extension operators (…) Simplify the code
Simplified array merge
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]
Copy the code
A copy of a single layer object
let 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'};
constcloneObj = {... obj};Copy the code
Find the maximum and minimum values in the array
// Shorthand
const arr = [2.8.15.4];
Math.max(... arr);/ / 15
Math.min(... arr);/ / 2
Copy the code
Use for in and for of to simplify normal for loops
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]);
}
Copy the code
Simplifies getting a character in a string
let str = 'jscurious.com';
//Longhand
str.charAt(2); // c
//Shorthand
str[2]; // c
Copy the code
Removing object properties
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}
Copy the code
Use arr. Filter (Boolean) to filter out the value of the array member falsey
let 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]
Copy the code
THE END
-
The articles (except the code) are organized in my own language and are abridged. If necessary, link to Amitav Mishra’s personal blog
-
In the body part of the code, Longhand indicates the normal form and Shorthand indicates the type
-
That’s all for this article. If you have any questions, please leave a comment at 🌹~