This article is based on years of experience with JavaScript coding techniques and is suitable for all developers who are programming with JavaScript.

The purpose of this article is to help you more skilled use of JavaScript language to develop work.

This paper will be divided into two parts, the primary and advanced, respectively.

 

Primary article

1. The ternary operator

Here is a good example of shortening a complete if statement to a single line of code.

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

Abbreviated to:

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

 

2. Loop statements

The following abbreviations can be useful when using pure JavaScript that does not rely on external libraries such as jQuery or LoDash.

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

Abbreviated to:

for (let index of allImgs)Copy the code

Here is an example of a shorthand for traversing forEach:

functionlogArrayElements(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

 

Declare variables

It is a good practice to assign values to variables before a function begins. When declaring multiple variables:

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

This can be abbreviated as:

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

 

4. If statement

You can omit the assignment operator when using if for basic judgments.

if (likeJavaScript === true)Copy the code

Abbreviated to:

if (likeJavaScript)Copy the code

 

5. Decimal numbers

You can use scientific notation to replace larger numbers, for example, you can abbreviate 10000000 to 1e7.

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

Abbreviated to:

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

 

6. Multi-line strings

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

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 to just use quotes:

const lorem =`Lorem ipsum dolor sit amet, consectetur adipisicing elit, seddoeiusmod 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 dolorin reprehenderit in voluptate velit esse.`Copy the code

 

Senior post

1. Variable assignment

When assigning a value from one variable to another, you first need to ensure that the original value is not null, undefined, or null.

This can be done by writing a statement containing multiple criteria:

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

Or abbreviated as:

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

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

let variable1;
let variable2 = variable1  || '';
console.log(variable2 = = = ");// prints true
variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints fooCopy the code

 

2. Assign the default value

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

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

Abbreviated to:

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

 

3. Object properties

ES6 provides a very simple way to assign attributes to objects. If the attribute name is the same as the key name, you can use shorthand.

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

Abbreviated to:

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

 

4. Arrow function

Classical functions are easy to read and write, but when they are nested in other functions, the whole function becomes a bit verbose and confusing. You can use the arrow function to abbreviate:

functionsayHello(name) { console.log('Hello', name); } setTimeout(function() { console.log('Loaded')},2000); list.forEach(function(item) { console.log(item); });Copy the code

Abbreviated to:

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

 

5. Implicit return values

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

To return multiline statements (such as object text), use () instead of {} to wrap the function body. This ensures that the code is evaluated as a single statement.

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

Abbreviated to:

calcCircumference = diameter =>( Math.PI* diameter;
)Copy the code

 

6. Default parameter values

You can use the if statement to define default values for function arguments. ES6 specifies that you can define default values in function declarations.

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

Abbreviated to:

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

 

7. Template string

We used to use the “+” to convert multiple variables to strings, but is there an easier way?

ES6 provides a way to synthesize variables into a string using backquotes and ${}.

const welcome = 'You have logged in as ' + first + ' ' + last + '.'
const db = 'http://' + host + ':' + port + '/' + database;Copy the code

Abbreviated to:

const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;Copy the code

 

8. Deconstruct assignment

Destruct assignment is an expression used to quickly extract property values from an array or object and assign them to defined variables.

In terms of code shorthand, deconstructing assignments can work well.

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

Abbreviated to:

import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity } = this.props;Copy the code

You can even specify your own variable name:

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

 

9. Expand operators

Expansion operators were introduced in ES6 to make JavaScript code more efficient and fun.

You can replace some array functions with the expansion 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( )Copy the code

Abbreviated to:

// 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(), the user can insert another array into any array using the extension operator.

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

You can also combine the expansion operator with the ES6 deconstruction symbol:

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

 

10. Mandatory parameters

By default, if no value is passed to a function parameter, JavaScript sets the function parameter to undefined. Others 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 arguments.”

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

Abbreviated to:

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

 

11, Array. The find

If you’ve ever written a find function in normal JavaScript, you’ve probably used a for loop. In ES6, we introduced a new array function called find (), which is shorthand for the 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) {
      returnpets[i]; }}}Copy the code

Abbreviated to:

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

 

[key] 12, Object

While it is common practice to write foo.bar as foo [‘bar’], it 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'})); // trueCopy the code

The above function does the job perfectly. But when there are many forms, validation needs to be applied, with different fields and rules. It would be a good choice if you could build a generic validation function that is configured at run time.

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

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. Two-bit operators

Bitwise operators are a basic part of JavaScript tutorials, but we don’t use bitwise operators very often. Because nobody wants to use ones and zeros when they’re not dealing with binary.

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

Math. Floor (4.9) = = = 4//trueCopy the code

Abbreviated to:

~ ~ 4.9 = = = 4//trueCopy the code

 

conclusion

These are some commonly used JavaScript shorthand tricks, and if there are others that haven’t been mentioned, you are welcome to add them.

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

Reproduced please indicate from: Grape city control

 

Related reading:

More than 100 sets of report templates are free to download

1 minute to choose the JavaScript framework that works best for you

Top 10 JavaScript editors, which one are you using?

 



This article is published by grape city control technology development team, reprint please indicate source: Grape city control

For more development tools and tips, please go to the official website of grape City controls

To learn about enterprise reporting and Web applications, visit the Grape City Enterprise Software website