Translator: myvin

The original link

This is really a must-read article for developers programming in the JavaScript language. I wrote this article as an important reference for quick JavaScript programming tips while learning JavaScript over the past few years. To help you understand, I’ve also given a programming perspective on the general writing.

June 14, 2017: This article is updated with some ES6-based shorthand. If you want to learn more about the new changes in ES6, sign up for SitePoint Premium and check out our video A Look into ES6.

1. Ternary operators

If you want to write an if.. Else expression, so this is a nice way to save code.

Conventional writing:

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

Copy the code

Shorthand:

`const answer = x > 10 ? 'is greater' : 'is lesser'; `Copy the code

You can also nest if expressions like this:

`const big = x > 10 ? "" greater 10"" : x`

Copy the code

2. Short-circuit evaluation shorthand

When assigning a variable to another variable, you may want to make sure that the variable is not null, undefined, or null. You can write a statement with multiple if expressions, or you can use short-circuit evaluation.

Conventional writing:

if (variable1 ! == null || variable1 ! == undefined || variable1 ! == '') { let variable2 = variable1; }Copy the code

Shorthand:

`const variable2 = variable1 || 'new'; `Copy the code

You don’t believe it works? Test it out for yourself (copy and paste the following code into es6Console) :

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true

variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo

Copy the code

3. Shorthand for variable declarations

This shorthand saves you a lot of time and space when you need to declare multiple variables simultaneously in a function.

Conventional writing:

let x;
let y;
let z = 3;

Copy the code

Shorthand:

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

4. If determine whether there is shorthand for the variable

This might be trivial, but it’s worth mentioning. The assignment operator can sometimes be omitted when we need to use if to determine whether a variable is true.

Conventional writing:

`if (likeJavaScript === true)`

Copy the code

Shorthand:

`if (likeJavaScript)`

Copy the code

** Note: ** These two examples are not exactly equal, and the expression works as long as the likeJavaScript variable is a true value.

Let me give you another example. If “” A “” does not equal true, the following:

Conventional writing:

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

Shorthand:

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

5. JavaScript loop shorthand

If you just want to run native JavaScript and don’t want to rely on external libraries like JQuery or LoDash, this tip is very useful.

Conventional writing:

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

Copy the code

Shorthand:

`for (let index in allImgs)`

Copy the code

Array. ForEach shorthand:

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

Copy the code

6. Short-circuit evaluation

If we don’t want to write six lines of code to assign a default value just to determine that a variable is null or undefined, we can use the short-circuit logic operator to do the same thing, and only one line of code.

Conventional writing:

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

Copy the code

Shorthand:

`const dbHost = process.env.DB_HOST || 'localhost'; `Copy the code

7. Decimal base index

You can see this written everywhere. This is a fancy way of writing it, without the zeros. For example, 1e7 means 1 followed by 7 zeros. This is a notation for the decimal base exponent (JavaScript interprets it as a floating-point type), which is equal to 10,000,000.

Conventional writing:

`for (let i = 0; i < 10000; i++) {}`

Copy the code

Shorthand:

for (let i = 0; i < 1e7; i++) {}

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

Copy the code

8. Object attribute shorthand

Defining object literals in JavaScript is very simple. ES6 provides a simpler way to define object properties. If name and key have the same name, then you can use the following shorthand.

Conventional writing:

`const obj = { x:x, y:y }; `Copy the code

Shorthand:

`const obj = { x, y }; `Copy the code

9. Shorthand for arrow functions

The classical method of writing functions is easy to read, but putting such functions into callbacks can be a bit verbose and confusing.

Conventional writing:

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

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

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

Copy the code

Shorthand:

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

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

list.forEach(item => console.log(item));

Copy the code

It is important to note that the value of this is completely different in the arrow function than in the normal writing function, so the two examples are not strictly equivalent. See this article on arrow Function syntax for more details.

Implicit return shorthand

We often use the return keyword to return the result of a function. Arrow functions with only one expression implicitly return the result of the function (the function must omit curly braces ({}) to omit the return keyword).

If you are returning a multi-line expression (such as an object literal), you need to wrap the function body with () instead of {}. This ensures that the code is evaluated and returned as a single expression.

Conventional writing:

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

Copy the code

Shorthand:

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

Copy the code

11. Default parameter values

You can use if expressions to define default values for function arguments. In ES6, you can define default values directly at function declaration time.

Conventional writing:

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

Copy the code

Shorthand:

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

volume(2) //output: 24

Copy the code

12. Template literals

Tired of using ‘+’ to concatenate multiple variables into a single string? Isn’t there an easier way to do this? If you can use ES6, congratulations, all you have to do is wrap your variables around backquotes and ${}.

Conventional writing:

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

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

Copy the code

Shorthand:

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

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

Copy the code

13. Deconstructing the shorthand of assignment

If you’re using any of the popular Web frameworks, chances are you’re using data in the form of arrays or object literals to pass information between components and apis. Once the component receives the data object, you need to expand it.

Conventional writing:

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

Shorthand:

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

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

Copy the code

You can even reassign variable names:

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

14. Multiline string shorthand

If you need to write multiple lines of strings in your code, you might write:

Conventional writing:

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

But there’s an easier way: use backquotes.

Shorthand:

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. Expand operator shorthand

The expansion operator was introduced in ES6 and has multiple applications that make JavaScript code more efficient and fun to use. It can be used to replace some array functions. The expansion operator is easy to write, just three points.

Conventional writing:

// 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

Shorthand:

// 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 concat(), you can insert an array anywhere in another array.

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

Copy the code

You can also use the expansion operator in conjunction with ES6 parsing assignments:

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. Compulsory parametric shorthand

JavaScript sets the function parameter to undefined by default if no value is passed. Some other programming languages throw warnings or errors. To force an argument, you can throw an error using an if expression if the argument is not defined, or you can use “force argument shorthand.”

Conventional writing:

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

Shorthand:

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

17. Array. Find shorthand

If you’ve ever written a lookup function in native JavaScript, you might use a for loop. In ES6, you can use a new method of arrays called find().

Conventional writing:

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

Shorthand:

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

Copy the code

18. The Object of shorthand

You know foo. bar can be written as Foo[‘bar’]. At first, there seems to be no reason why it should be written this way. But this allows you to write reusable code.

Consider the next simple example of 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

This function does exactly what you need. However, consider a scenario where you have many forms to validate, and different fields have different validation rules. Wouldn’t it be better to create a generic validation function that is configured at run time?

Shorthand:

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

You have now created a validation function that can be reused across all forms, rather than having to write a specific validation function for each form.

19. Dichotomy of inverse operators

Bitwise operators are a feature you learn about when you first learn JavaScript, but you’ll almost never use them if you don’t deal with binaries.

However, two-bit operators have a very useful use case: they can be used instead of math.floor. The advantage of the two-bit inverse operator is that it performs the same operation faster. You can check out more about bitwise operators here.

Conventional writing:

` math.h floor (4.9) = = = 4 / / true `Copy the code

Shorthand:

` ~ ~ 4.9 = = = 4 / / true `Copy the code

20. Any other tips?

I do like these tips, and I’d love to find more. If you have something to say, just leave a message!