1. Ternary operators

When trying to write an if… Else statements, use the ternary operator instead.

const x = 20;
let answer;
if (x > 10) {
    answer = 'is greater';
} else {
    answer = 'is lesser';
}Copy the code

Const answer = x > 10? ‘is greater’ : ‘is lesser’;

We can also nest if statements: const big = x > 10? ” greater 10″ : x

2. Short circuit evaluation shorthand

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; }Copy the code

Or you can use a short-circuit evaluation methods: const variable2 = variable1 | | ‘new’;

3. Declare variable abbreviations

let x;
let y;
let z = 3;Copy the code

Let x, y, z=3;

4. If there is a conditional shorthand method

if (likeJavaScript === true)

– If (likeJavaScript)

The two statements are equal only if likeJavaScript is true

If the judgment value is not true, we can do this:

let a; if ( a ! == true ) { // do something... }Copy the code

Abbreviations:

let a; if ( ! a ) { // do something... }Copy the code

5.JavaScript looping shorthand method

for (let i = 0; i < allImgs.length; i++)

Short: for (let index in allImgs) 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] = 9Copy the code

6. Short-circuit evaluation

Assign a value to a variable by checking whether it is null or undefined:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}Copy the code

Abbreviations: const dbHost = process. The env. DB_HOST | | ‘localhost’.

7. Decimal indices

When you need to write a number with lots of zeros (such as 10000000), you can use an exponent (1e7) instead of the number: for (let I = 0; i < 10000; I++) {}

for (let i = 0; i < 1e7; E0 === 1; 1e1 === 10; 1e2 === 100; 1e3 === 1000; 1e4 === 10000; 1e5 === 100000;Copy the code

8. Object property shorthand

Const obj = {x:x, y:y}; const obj = {x:x, y:y};

Const obj = {x, y};

9. Shorthand for arrow functions

The traditional method of writing functions is easy to understand and write, but when nested in another function, these advantages are lost.

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});Copy the code

Abbreviations:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));Copy the code

10. Implicit return value shorthand

Return statements are often used to return the final result of a function. The arrow function of a single statement can implicitly return its value (the function must omit {} to omit the return keyword).

To return multiline statements (such as object literal expressions), enclose the function body with ().

function calcCircumference(diameter) {
  return Math.PI * diameter
}

var func = function func() {
  return { foo: 1 };
};Copy the code

Abbreviations:

calcCircumference = diameter => (
  Math.PI * diameter;
)

var func = () => ({ foo: 1 });Copy the code

11. Default parameter values

To pass default values to arguments in a function, it is usually written using an if statement, but using ES6 to define default values is succinct:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}Copy the code

Abbreviations:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24Copy the code

12. Template string

In traditional JavaScript languages, output templates are written like this.

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;Copy the code

ES6 can use backquotes and ${} abbreviations:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;Copy the code

13. Deconstruct the assignment shorthand

In web frameworks, you often need to pass data in the literal form of an array or object back and forth between components and apis, and then 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;Copy the code

Abbreviations:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;Copy the code

Variable names can also be assigned:

const { store, form, loading, errors, entity:contact } = this.props; // The last variable is contactCopy the code

14. Multiline string shorthand

To print a multi-line string, concatenate it with + :

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'Copy the code

Use back quotes to abbreviate:

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.`Copy the code

15. Extended operator shorthand

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()Copy the code

Abbreviations:

// 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];Copy the code

Unlike the concat() function, you can use the extension operator to insert another array anywhere in an array.

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];Copy the code

It can also be destructed using the extension operator:

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 }Copy the code

16. Mandatory parameter abbreviations

If no value is passed to a function parameter in JavaScript, the parameter is undefined. To enhance parameter assignment, you can use an if statement to throw an exception, or use a mandatory parameter shorthand method.

function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter! '); } return bar; }Copy the code

Abbreviations:

mandatory = () => { throw new Error('Missing parameter! '); } foo = (bar = mandatory()) => { return bar; }Copy the code

17. Array. A find shorthand

To find a value from an array, you loop. In ES6, the find() function can do the same.

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]; }}}Copy the code

Abbreviations:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }Copy the code

18. The Object [key] shorthand

Consider a validation function

function validate(values) { if(! values.first) return false; if(! values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // trueCopy the code

Suppose that when different fields and rules are needed for validation, can you write a generic function to validate at run time?

// Object validation rule const schema = {first: {required:true}, last: {required:true}} // 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'})); // trueCopy the code

You can now have validation functions that work for a variety of situations, and you don’t need to write custom validation functions for each one

19. Abbreviation for double nonbit operations

There is a valid use case for dual non-operational operators. Can be used instead of math.floor (), which has the advantage of being faster. Read this article to learn more about multiple operations. Math. Floor (4.9) = = = 4 / / true

Short: ~~4.9 === 4 //true

SitePoint: www.sitepoint.com/sho…