This is a must read for any JavaScript-based developer. I have used this article as an important reference for learning shorthand JavaScript coding techniques that I have mastered over the years. To help you understand what's happening, I've included some long-term versions to provide some coding perspectives.
1. Ternary operators
When you want to write if... When an else statement is executed, a ternary operator is used instead.
const x = 20;
let answer;
if (x > 10) {
answer = 'is greater';
} else {
answer = 'is lesser';
}
Abbreviation:
const answer = x > 10 ? 'is greater' : 'is lesser';
You can also nest if statements:
const big = x > 10 ? " greater 10" : x
2. Short Circuit Evaluation
When assigning another value to a variable, you want to make sure that the source starting value is not null, undefined or null. You can write an if statement with multiple conditions.
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
Or a short-circuit evaluation method can be used:
const variable2 = variable1 || 'new';
3. Short Writing Method for Declaring Variables
let x;
let y;
let z = 3;
Method of abbreviation:
let x, y, z=3;
4. Short Writing Method of if Existence Conditions
if (likeJavaScript === true)
Abbreviation:
if (likeJavaScript)
Only if like JavaScript is a truth value can the two statements be equal
If the judgement value is not the true value, it can be as follows:
let a;
if ( a !== true ) {
// do something...
}
Abbreviation:
let a;
if ( !a ) {
// do something...
}
5.JavaScript loop abbreviation method
for (let i = 0; i < allImgs.length; i++)
Abbreviation:
for (let index in allImgs)
You can also use Array.forEach:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
6. Short Circuit Evaluation
The value assigned to a variable is determined by whether its value is null or undefined.
let dbHost;
if (process.env.DB_HOST) {
dbHost = process.env.DB_HOST;
} else {
dbHost = 'localhost';
}
Abbreviation:
const dbHost = process.env.DB_HOST || 'localhost';
7. decimal index
When a number needs to be written with many zeros (e.g. 10000000), the index (1e7) can be used instead of the number:
for (let i = 0; i < 10000; i++) {}
Abbreviation:
for (let i = 0; i < 1e7; i++) {}
// The following are all returns to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
8. Object Attribute Abbreviation
If the attribute name is the same as the key name, ES6 can be used:
const obj = { x:x, y:y };
Abbreviation:
const obj = { x, y };
9. Abbreviation of Arrow Function
Traditional function writing methods are easy to understand and write, but when nested in another function, these advantages disappear.
function sayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item) {
console.log(item);
});
Abbreviation:
sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));
10. Implicit return value abbreviation
The return statement is often used to return the final result of a function, and the arrow function of a single statement can implicitly return its value (the function must omit {} in order to omit the return keyword)
To return a multi-line statement, such as an object literal expression, you need to surround the function body with ().
function calcCircumference(diameter) {
return Math.PI * diameter
}
var func = function func() {
return { foo: 1 };
};
Abbreviation:
calcCircumference = diameter => (
Math.PI * diameter;
)
var func = () => ({ foo: 1 });
11. Default parameter values
In order to pass default values to parameters in functions, if statements are usually used, but defining default values using ES6 is very concise:
function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
Abbreviation:
volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24
12. Template string
In traditional JavaScript languages, output templates are usually written in this way.
const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;
ES6 can be abbreviated using inversion marks and ${}:
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;
13. Deconstruction assignment abbreviation method
In web frameworks, you often need to pass array or object literal data back and forth between components and API s, and then you need to deconstruct it.
const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');
const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;
Abbreviation:
import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;
Variable names can also be assigned:
const { store, form, loading, errors, entity:contact } = this.props;
//The last variable is called contact.
14. Multi-line string abbreviation
We need to output multi-line strings, and we need to use + to stitch:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
+ 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
+ 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
+ 'veniam, quis nostrud exercitation ullamco laboris\n\t'
+ 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
+ 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
The use of back quotation marks can achieve the purpose of simplification:
const lorem = `Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse.`
15. Abbreviation of Extended Operators
Extension operators have several use cases to make JavaScript code more efficient and can be used instead of an array function.
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
Abbreviation:
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
Unlike the concat() function, you can use an extension operator to insert another array anywhere in an array.
const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
Extended operators can also be used to deconstruct:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
16. Compulsory parameter abbreviation
If no value is passed to the function parameter in JavaScript, the parameter is undefined. To enhance parameter assignment, you can use the if statement to throw exceptions, or use the forced parameter abbreviation method.
function foo(bar) {
if(bar === undefined) {
throw new Error('Missing parameter!');
}
return bar;
}
Abbreviation:
mandatory = () => {
throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
return bar;
}
17.Array.find
To find a value from an array, you need a loop. In ES6, the find() function can achieve the same effect.
const pets = [
{ type: 'Dog', name: 'Max'},
{ type: 'Cat', name: 'Karl'},
{ type: 'Dog', name: 'Tommy'},
]
function findDog(name) {
for(let i = 0; i<pets.length; ++i) {
if(pets[i].type === 'Dog' && pets[i].name === name) {
return pets[i];
}
}
}
Abbreviation:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }
18.Object[key] abbreviation
Consider a verification function
function validate(values) {
if(!values.first)
return false;
if(!values.last)
return false;
return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true
Assuming that different domains and rules are needed to validate, can a general function be written to validate at runtime?
// Object Validation Rules
const schema = {
first: {
required:true
},
last: {
required:true
}
}
// Universal Verification Function
const validate = (schema, values) => {
for(field in schema) {
if(schema[field].required) {
if(!values[field]) {
return false;
}
}
}
return true;
}
console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
Now you can have validation functions for various situations, and you don't need to write custom validation functions for each one.
19. Abbreviation of Double Non-Bit Operations
There is a valid use case for double non-operator. It can be used instead of Math.floor(), and its advantage is that it runs faster. You can read this article to learn more bit operations.
Math.floor(4.9) === 4 //true
Abbreviation
~~4.9 === 4 //true
Translation Address: https://juejin.im/post/5948db9661ff4b006c061b2b
Original address: https://www.sitepoint.com/shorthand-javascript-techniques/