Shorthand tricks JavaScript developers need to know

Beginners


1. Ternary operator

Here's a good example of a complete if statement, shortened to a single line of code.

const x = 20;

let answer;

if (x > 10) {

    answer = 'greater than 10';

} else {

    answer = 'less than 10';

}

Abbreviated as:

const answer = x > 10 ? 'greater than 10' : 'less than 10';


2. Loop statement

The following shorthand can be very useful when working with pure JavaScript (without relying on external libraries like jQuery or lodash).

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

Abbreviated as:

for (let index of allImgs)


Here is a shorthand example of iterating over an 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


3. Declare variables

It is good practice to assign values ​​to variables before the function starts. When declaring multiple variables:

let x;

let y;

flight z = 3;

Can be abbreviated as:

let x, y, z=3;


4. if statement

When using if to make basic judgments, the assignment operator can be omitted.

if (likeJavaScript === true)

Abbreviated as:

if (likeJavaScript)


5. Decimal numbers

Scientific notation can be used in place of larger data, eg 10000000 can be abbreviated as 1e7.

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

Abbreviated as:

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


6. Multi-line strings

If you need to write a multi-line string in your code, like this:

const lorem = 'Love the pain

    + 'Going back to the game, but I don\'t\n't'

    + 'like toil and obesity' For the least\n\t'

    + "I will come, what can our school district do?"

    + 'but to achieve the objectives from it's advantage. normal but\n\t'

    + 'the pain in the nose accuses you of wanting to be in pleasure.\n\t'

But there is an easier way, just using quotes:

const lorem = `Investing in pain

    rebates, but give it as low as time

    such as fatigue and obesity. In order to have at least one

    pardon, what is our school district employment

    if not to achieve the objectives from it. homework

    he wants to be in pleasure.`



Advanced


1. Variable assignment

When assigning the value of one variable to another, you first need to make sure that the original value is not null, undefined, or null.


This can be achieved by writing a judgment statement containing multiple conditions

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {

     let variable2 = variable1;

}

Or abbreviated as:

const variable2 = variable1  || 'new';

You can paste the following code into es6console and test it yourself:

let variable1;

let variable2 = variable1  || '';

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

variable1 = 'foo';

variable2 = variable1  || '';

console.log(variable2); // prints foo


2. Default value assignment

If the expected parameter is null or undefined, you don't need to write six lines of code to assign a default value. We can do the same thing with just one line of code using just a short logical operator.

let dbHost;

if (process.env.DB_HOST) {

  dbHost = process.env.DB_HOST;

} else {

  dbHost = 'localhost';

}

Abbreviated as:

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


3. Object properties

ES6 provides an easy way to assign properties to objects. A shorthand can be used if the property name is the same as the key name.

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

Abbreviated as:

const obj = { x, y };


4. Arrow function

Classical functions are easy to read and write, but when they are nested within other functions and called, the whole function can become somewhat verbose and confusing. This can be shortened using arrow functions:

function sayHello(name) {

  console.log('Hello', name);

}

 

setTimeout(function() {

  console.log('Loaded')

}, 2000);

 

list.forEach(function(item) {

  console.log(item);

});

Abbreviated as:

sayHello = name => console.log('Hello', name);
setTimeout(() => console.log('Loaded'), 2000);list.forEach(item => console.log(item));


5. Implicit return value

Return value is the keyword we usually use to return the final result of a function. An arrow function with only one statement that can return a result implicitly (the function must omit the parentheses ({ }) in order to omit the return keyword).


To return a multi-line statement (such as an object literal), you need to wrap the function body with ( ) instead of { }. This ensures that the code is evaluated as a single statement.

function calcCircumference(diameter) {

  return Math.PI * diameter

}

Abbreviated as:

calcCircumference = diameter => (

  Math.PI * diameter;

)


6. Default parameter value

You can use an if statement to define default values ​​for function parameters. ES6 specifies that default values ​​can be defined in function declarations.

function volume(l, w, h) {

  if (w === undefined)

    w = 3;

  if (h === undefined)

    h = 4;

  return l * w * h;

}

Abbreviated as:

volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24


7. Template string

We used to use "+" to convert multiple variables to strings in the past, but is there an easier way?


ES6 provides a corresponding method, we can use backticks and $ { } to combine variables into a string.

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

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

abbreviated as

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

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


8. Destructuring assignment

Destructuring assignment is an expression used to quickly extract a property value from an array or object and assign it to a defined variable.


In terms of code shorthand, destructuring assignment can achieve very good results.

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;

Abbreviated as:

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

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

You can even specify your own variable names:

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


9. Spread operator

The spread operator was introduced in ES6, and using the spread operator can make JavaScript code more efficient and interesting.


Some array functions can be replaced using the spread operator.

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

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

Unlike the concat( ) function, the user can use the spread operator to insert any array into another array.

const odd = [1, 3, 5 ];

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

It is also possible to combine the spread operator with ES6 destructuring notation:

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 }


10. Mandatory parameters

By default, JavaScript sets function parameters to undefined if no value is passed to them. Other languages ​​will issue warnings or errors. To perform parameter assignment, you can use an if statement to throw an undefined error, or you can take advantage of "mandatory parameters".

function foo(bar) {

  if(bar === undefined) {

    throw new Error('Missing parameter!');

  }

  return bar;

}

Abbreviated as:

mandatory = ( ) => {

  throw new Error('Missing parameter!');

}

foo = (bar = mandatory( )) => {

  return bar;

}


11、Array.find

If you've ever written a find function in plain JavaScript, you probably used a for loop. In ES6, a new array function called find() was introduced that implements a shorthand for a for loop.

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

    }

  }

}

Abbreviated as:

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


12、Object [key]

While it is common practice to write foo.bar as foo['bar'], this practice forms the basis for writing reusable code.


Consider the following simplified 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'})); // true

The above function completes the verification work perfectly. But when there are many forms, validation needs to be applied, and there are different fields and rules. It would be a good choice if it was possible to build a generic validation function that was configured at runtime.

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

Now that we have this validation function, we can reuse it across all forms without having to write a custom validation function for each form.


13. Double bit operator

Bitwise operators are the basics of JavaScript introductory tutorials, but we don't use bitwise operators very often. Because nobody wants to use 1s and 0s without dealing with binary.


But there is a useful case for the two-bit operator. You can use the two-bit operator instead of Math.floor( ). The advantage of the double negation bitwise operator is that it performs the same operation faster.

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

Abbreviated as:

~~4.9 === 4  //true


Recommended JavaScript development tools

SpreadJS pure front-end table control is an HTML5-based JavaScript spreadsheet and grid function control, providing a complete formula engine, sorting, filtering, input controls, data visualization, Excel import/export and other functions, suitable for .NET, Java and mobile Table program development for online editing of Excel-like functions on various platforms such as the terminal.


Original link: https://www.sitepoint.com/shorthand-javascript-techniques/


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326265421&siteId=291194637