The blogger said: For any based on _____________ JavaScript For developers, this is absolutely a must-read article and a magic weapon to improve development efficiency.
text
1. Ternary Operator
When you want to write if...else statements in one line of code, it is a good choice to use ternary operators, such as:
const x = 20;
let answer;
if (x > 10) {
answer = 'is greater';
} else {
answer = 'is lesser';
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It can be abbreviated as:
const answer = x > 10 ? 'is greater' : 'is lesser';
- 1
- 1
You can also nest if statements:
const big = x > 10 ? " greater 10" : x
- 1
- 1
2. Short circuit evaluation
When assigning another value to a variable, you may want to make sure that the initial value is not null, undefined or null. At this point, you can write an if statement with multiple conditions:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
- 1
- 2
- 3
- 1
- 2
- 3
Or a short-circuit evaluation method can be used:
const variable2 = variable1 || 'new';
- 1
- 1
3. Abbreviated variable declaration
When defining a function, you may need to declare multiple variables first, such as:
let x;
let y;
let z = 3;
- 1
- 2
- 3
- 1
- 2
- 3
At this point, you can use abbreviation to save a lot of time and space, that is, declare multiple variables at the same time:
let x, y, z=3;
- 1
- 1
4. Short description of if execution conditions
This may be insignificant, but it is worth mentioning. When you do if condition checking, its assignment operation can be omitted, for example:
if (likeJavaScript === true)
- 1
- 1
It can be abbreviated as:
if (likeJavaScript)
- 1
- 1
The above two statements can be replaced only if like JavaScript is a true value. If a false value is judged, for example:
let a;
if ( a !== true ) {
// do something...
}
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
It can be abbreviated as:
let a;
if ( !a ) {
// do something...
}
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
5. Short-hand JavaScript Loop Method
When you want to use pure javascript Not dependent on external libraries (e.g. jQuery ) This is very useful at times.
for (let i = 0; i < allImgs.length; i++)
- 1
- 1
It can be abbreviated as:
for (let index in allImgs)
- 1
- 1
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
6. Short Circuit Evaluation
If we want to assign the default value by judging whether the parameter is null or undefined, instead of writing six lines of code, we can use a short-circuit logic operator to perform the same operation with only one line of code. For example:
let dbHost;
if (process.env.DB_HOST) {
dbHost = process.env.DB_HOST;
} else {
dbHost = 'localhost';
}
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
It can be abbreviated as:
const dbHost = process.env.DB_HOST || 'localhost';
- 1
- 1
7. decimal index
When the tail of a number is many zeros (e.g. 10000000), we can use the index (1e7) instead of the number, e.g.
for (let i = 0; i < 10000; i++) {}
- 1
- 1
It can be abbreviated as:
for (let i = 0; i < 1e7; i++) {}
// Here are all returns true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
8. Short Object Properties
Defining objects in JavaScript is simple, and ES6 provides a simpler way to assign object attributes. If the attribute name is the same as the key value, for example:
const obj = { x:x, y:y };
- 1
- 1
It can be abbreviated as:
const obj = { x, y };
- 1
- 1
9. Short Arrow Function
Traditional functions are easy to understand and write, but when they are nested in another function, they become verbose and confusing. For example:
function sayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
}, 2000);
list.forEach(function(item) {
console.log(item);
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
At this time, it can be abbreviated as:
sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);
list.forEach(item => console.log(item));
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
10. Short-hand implicit return value
We often use return statements to return the final result of a function, and only one line of arrow functions declaring statements can implicitly return its value (at this point the function must omit {} in order to omit the return keyword). If you want to return a multi-line statement, you need to surround the body of the function with (). For example:
function calcCircumference(diameter) {
return Math.PI * diameter
}
var func = function func() {
return { foo: 1 };
};
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It can be abbreviated as:
calcCircumference = diameter => (
Math.PI * diameter;
)
var func = () => ({ foo: 1 });
- 1
- 2
- 3
- 4
- 5
- 1
- 2
- 3
- 4
- 5
11. Default parameter values
We often use if statements to define default values for parameters in functions. But in ES6, we can declare the default values of parameters in the function itself. For example:
function volume(l, w, h) {
if (w === undefined)
w = 3;
if (h === undefined)
h = 4;
return l * w * h;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It can be abbreviated as:
volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) // output: 24
- 1
- 2
- 3
- 1
- 2
- 3
12. String Template
Are you tired of using + to convert multiple variables into strings? Is there a simpler way? If you can use ES6, then fortunately, you only need to use inversion marks and put variables in ${}. For example:
const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;
- 1
- 2
- 3
- 1
- 2
- 3
It can be abbreviated as:
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;
- 1
- 2
- 3
- 1
- 2
- 3
13. Abbreviated Assignment Method
If you are using any popular Web framework, you are likely to use arrays or objects to communicate data between components and API s in the form of this article. Once the data object reaches a component, you need to decompress it. For example:
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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
It can be abbreviated as:
import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;
- 1
- 2
- 3
- 1
- 2
- 3
Variable names can also be assigned:
// The last variable is called contact.
const { store, form, loading, errors, entity:contact } = this.props;
- 1
- 2
- 3
- 1
- 2
- 3
14. Short multi-line strings
If you've ever found that you need to write multi-line strings in your code, that's probably how you write them, splicing + between output multi-line strings:
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'
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
But if you use back quotation marks, you can achieve the purpose of abbreviation:
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.`
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
15. Extended Operator
In ES6, including extension operators, it can make your operation easier, for example:
// 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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It can be abbreviated as:
// 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];
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Unlike the concat() function, you can use an extension operator to insert another array anywhere in an array, for example:
const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4, 6];
- 1
- 2
- 1
- 2
Extension operators can also be used:
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 }
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
16. Forced parameters
By default, if no value is passed, JavaScript sets the function parameter to undefined, while other languages report warnings or errors. To perform parameter assignment, you can either have the if statement throw an undefined error or use the "coercive parameter" method. For example:
function foo(bar) {
if(bar === undefined) {
throw new Error('Missing parameter!');
}
return bar;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
It can be abbreviated as:
mandatory = () => {
throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
return bar;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 1
- 2
- 3
- 4
- 5
- 6
- 7
17. Array.find
If you've ever been responsible for writing find functions in JavaScript, you've probably used the for loop. Here, we introduce an array function named find() in ES6.
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];
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
It can be abbreviated as:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }
- 1
- 2
- 1
- 2
18. Short for Object[key]
Do you know that Foo.bar can also be written as Foo['bar']? At first, there seemed to be no reason for you to write like that. However, this symbol gives you the basis for writing reusable code. Consider the following simplified examples of validation functions:
function validate(values) {
if(!values.first)
return false;
if(!values.last)
return false;
return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
This function can accomplish its task perfectly. However, considering a scenario, you have many forms that you need to validate, but there are different fields and rules. So, isn't it good to build a general validation function that can be configured 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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Now we have a validation function that can be reused in all forms without having to write a custom validation function for each form.
19. Short for double bitwise non-operators
Bit-by-bit operators are absolutely operators you learned when you first learned JavaScript, but they have never been useful. Because if you don't deal with binary, who's going to have nothing to do with 0 and 1? However, double bitwise non-operators are very useful, for example, you can use them instead of floor() functions, and bitwise operators operate faster than other similar operations.
Math.floor(4.9) === 4 //true
- 1
- 1
It can be abbreviated as:
~~4.9 === 4 //true
- 1
- 1
20. Suggest One of U?
I like these shorthand methods very much, and hope to find more shorthand methods, if you know, please leave your comments!
Beijing laser freckle removal: http://www.6ysh.com/