Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

19 elegant JavaScript shorthand tips


May 31, 2021 Article blog


Table of contents


This article is from the public number: JavaScript Ninja Cheats, by Luck Day

As a programmer, I've always wanted to have some tips for reducing the amount of code, and today's article brings you 19 JavaScript shorthand tips.

1. Mitso operator

When you want to write if...else When you use a mitso operator instead of an else statement.

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

    

Shorthand:

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 shorthand

When assigning another value to a variable, you want to determine that the source start value is not null, undefined, or empty. You can write an if statement that composes a multiple criteria.

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

    

Alternatively, you can use a short-circuit evaluation method:

const variable2 = variable1 || 'new';

3. Declare the variable shorthand method

    let x;
    let y;
    let z = 3;

Shorthand:

let x, y, z=3;

4.if exists conditional shorthand method

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

Statements are equal only if likeJavaScript is true

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

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

Shorthand:

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

5. JavaScript loop shorthand method

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

Shorthand:

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

A variable is assigned a value by determining whether its value is null or undefined, you can:

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

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost';

7. Decimal Index

When you need to write a number band with a lot of zeros (e.g. 10000000), you can replace that number with an exponent (1e7): for (let i = 0; i < 10000; i++) {}

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

    
    // 下面都是返回true
    1e0 === 1;
    1e1 === 10;
    1e2 === 100;
    1e3 === 1000;
    1e4 === 10000;
    1e5 === 100000;

8. Shorthand for object properties

If the property name is the same as the key name, you can take the ES6 approach:

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

Shorthand:

const obj = { x, y };

9. Arrow function shorthand

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);
    });

    

Shorthand:

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

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

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

    

10. Implicitly returns a shorthand for the value

Return return are often used to return the final result of a function, and an arrow function with a separate statement can implicitly return its value (the function must 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 };
    };

    

Shorthand:

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

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

    

11. Default parameter value

In order to pass default values to arguments in a function, it is usually written using an if statement, but defining the default value using ES6 is succinct:

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

Shorthand:

    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 like this.

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

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

ES6 can use 反引号 and ${}

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

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

13. Deconstruction assignment shorthand method

In a web framework, you often need to pass data in 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;

Shorthand:

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

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

You can also assign variable names:

    const { store, form, loading, errors, entity:contact } = this.props;
    //最后一个变量名为contact

14. Multi-line string shorthand

You need to output a multi-line string, and you need to stitch it together 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'

With backquotes, you can achieve 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.`

15. Extended operator shorthand

There are several use cases for extension operators that 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()

    

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];

    

Unlike concat() functions, you can use extension operators to insert another array anywhere in an array.

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

    

You can also use extension operators 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. Force parameter shorthand

If a value is not passed to a function argument in JavaScript, the argument is underfined. To enhance parameter assignment, you can use an if statement to throw an exception, or use a forced parameter shorthand method.

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

Shorthand:

    mandatory = () => {
      throw new Error('Missing parameter!');
    }

    
    foo = (bar = mandatory()) => {
      return bar;
    }

17.Array.find shorthand

To find a value from an array, you need a loop. In ES6, the find() function does 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];
        }
      }
    }

Shorthand:

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

18.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'})); // true

Assuming that different domains and rules are required to validate, can you write a generic function to confirm at runtime?

    // 对象验证规则
    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'})); // true

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

19. Double non-bit operation shorthand

There is a valid use case for dual non-operators. Can be used instead of Math.floor() for the advantage of running faster.

Math.floor(4.9) === 4 //true

Shorthand:

~~4.9 === 4 //true

Here's a look at W3Cschool编程狮 introduction to 19 elegant JavaScript shorthand tips.