JavaScript Short-hand Techniques

Posted by tdnxxx444 on Tue, 09 Jul 2019 23:15:14 +0200

This article is based on years of experience in JavaScript coding technology and is suitable for all developers who are using JavaScript programming.

The purpose of this article is to help you more skilled in using JavaScript language for development work.

The article will be divided into two parts: the first part and the senior part, which will be introduced separately.

Preliminary Chapter
1. Trinomial Operator
Here is a good example of a complete if statement, abbreviated as a 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 abbreviations are useful when using pure JavaScript (independent of external libraries such as jQuery or lodash).

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

Abbreviated as:

for (let index of allImgs)

Following is a short example of traversing the 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 a good habit to assign variables before a function starts. When declaring multiple variables:

let x;
let y;
let z = 3;

It can be abbreviated as:

let x, y, z=3;

4. if statement
The assignment operator can be omitted when basic judgment is made by using if.

if (likeJavaScript === true)

Abbreviated as:

if (likeJavaScript)

5. decimal number
The larger data can be replaced by scientific counting, for example, 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 string
If you need to write multi-line strings in your code, as follows:

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'
But there's a simpler way, using quotation marks only:

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.`

            web Front-end development resources Q-q-u-n:  767273102 ,There are free development tools, zero foundation, advanced video tutorials, hope novice less detours

Advanced Chapter

1. Variable assignment
When assigning the value of one variable to another, you first need to ensure that the original value is not null, undefined, or null.

It can be achieved by writing a judgment statement with multiple conditions:

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

Or abbreviate it in the following form:

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, there is no need to write six lines of code to assign default values. We can do the same thing with only one line of code, using only one 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 attributes

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

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

Abbreviated as:

const obj = { x, y };

4. Arrow function

Classical functions are easy to read and write, but if they are nested in other functions to be called, the whole function becomes a bit verbose and confusing. At this point, you can use the arrow function to abbreviate:

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

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

To return multi-line statements (such as object text), you need to wrap the body of the function 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 values

Default values of function parameters can be defined using the if statement. 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

In the past, we used to use "+" to convert multiple variables into strings, but is there a simpler way?

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

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. Deconstruction assignment

Deconstruction assignment is an expression used to quickly extract attribute values from arrays or objects and assign defined variables.

In terms of code abbreviation, deconstruction assignment can achieve 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 name:

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

9. Expansion Operator

Expansion operators were introduced in ES6, and using them can make JavaScript code more efficient and interesting.

Some array functions can be replaced by expansion operators.

// 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 concat(), users can insert another array in any array using an extension operator.

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

Expansion operators can also be combined with ES6 deconstruction symbols:

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. Forced parameters

By default, if you don't pass values to function parameters, JavaScript sets function parameters to undefined. Other languages may issue warnings or errors. To perform parameter assignment, you can use the if statement to throw undefined errors, or you can use "coercive 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 find functions in plain JavaScript, you might use for loops. In ES6, a new array function named find () is introduced, which can abbreviate 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];
    }
  }
}

12,Object [key]

Although writing foo.bar as foo ['bar'] is a common practice, 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'})); // true

The above function completes the verification perfectly. But when there are many forms, validation needs to be applied, with different fields and rules. If you can build a generic validation function that is configured at run time, it's a good choice.

// 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 in all forms without having to write custom validation functions for each form. web front-end development resources Q-q-u-n:767273102, with free development tools, zero-based, advanced video tutorials, hope novice less detours

13. Bibit Operator

Bit operators are the basics of JavaScript beginner tutorials, but we don't use them very often. Because no one wants to use 1 and 0 without dealing with binary.

But the two-bit operator has a very practical case. You can use a two-bit operator instead of Math.floor(). The advantage of the double negative bit operator is that it performs the same operation faster.

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

Abbreviated as:

~~4.9 === 4  //true

Recommendation of JavaScript Development Tools

SpreadJS pure front-end form control is based on HTML5 JavaScript spreadsheet and grid function control. It provides complete functions such as formula engine, sorting, filtering, input control, data visualization, Excel import/export, etc. It is suitable for online editing Excel functions of. NET, Java and mobile platforms. Sequence development.

These are some common JavaScript abbreviation techniques. If there are other abbreviation techniques that are not mentioned, you are welcome to add them.

Topics: Javascript less Attribute Database