Home > Web Front-end > JS Tutorial > Shorthand tips that JavaScript developers need to know (advanced)

Shorthand tips that JavaScript developers need to know (advanced)

云罗郡主
Release: 2018-10-19 14:41:40
forward
1967 people have browsed it

This article brings you the abbreviation skills that JavaScript developers need to know (advanced). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Variable assignment

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

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

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

or abbreviated to the following form:

const variable2 = variable1  || 'new';
Copy after login

You can paste the following code into es6console , Test by yourself:

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true
variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo
Copy after login

2. Default value assignment

If the expected parameter is null or undefined, there is no need to write six lines of code to assign a default value. We can accomplish the same operation in 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';
}
Copy after login

The abbreviation is:

const dbHost = process.env.DB_HOST || 'localhost';
Copy after login

3. Object attributes

ES6 provides a very simple way to assign attributes to objects. If the property name is the same as the key name, the abbreviation can be used.

const obj = { x:x, y:y };
Copy after login

The abbreviation is:

const obj = { x, y };
Copy after login

4. Arrow function

Classic functions are easy to read and write, but if they are nested in other functions and called, the entire function It can get a little long and confusing. At this time, you can use the arrow function to abbreviate it:

function sayHello(name) {
  console.log('Hello', name);
}
 
setTimeout(function() {
  console.log('Loaded')
}, 2000);
 
list.forEach(function(item) {
  console.log(item);
});
Copy after login

The abbreviation is:

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

5. Implicit return value

The return value is what we usually use to return the final result of the function Keywords. An arrow function with only one statement 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 object text), you need to 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 after login

The abbreviation is:

calcCircumference = diameter => (
  Math.PI * diameter;
)
Copy after login

6. Default parameter value

You can use the if statement to define the default value of the function parameter. ES6 provides 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;
}
Copy after login

The abbreviation is:

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

7. Template string

In the past, we were used to using " " to convert multiple variables into strings, but is there a simpler way? What about the method?

ES6 provides corresponding methods, 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;
Copy after login

The abbreviation is:

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

8. Destructuring assignment

Destructuring assignment is an expression used to quickly extract attribute values ​​from an array or object and assign them to defined variables.

In terms of code abbreviation, destructuring 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;
Copy after login

The abbreviation is:

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

You can even specify your own variable name:

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

9. Expansion operator

The expansion operator is in ES6 Introduced, using the spread operator can make JavaScript code more efficient and interesting.

Some array functions can be replaced by 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( )
Copy after login

The abbreviation is:

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

The difference between the functions of concat() and concat() is that the user can use the spread operator to insert another array into any array.

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

You can also use the expansion operator in combination with ES6 destructuring 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 }
Copy after login

10. Mandatory parameters

By default, if no value is passed to the function parameter, then JavaScript will set the function parameters to undefined. 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 "forced parameters".

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

The abbreviation is:

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

11. Array.find

If you have ever written the find function in ordinary JavaScript, then you may have used a for loop. In ES6, a new array function called find() was introduced, which is shorthand for implementing 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 === &#39;Dog&#39; && pets[i].name === name) {
      return pets[i];
    }
  }
}
Copy after login

The abbreviation is:

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

12. Object [key]

Although it is a common practice to write foo.bar as foo ['bar'], this These practices form the basis for writing reusable code.

Please consider the following simplified example of a verification function:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}
console.log(validate({first:'Bruce',last:'Wayne'})); // true
Copy after login

The above function completes the verification work perfectly. But when there are many forms, validation needs to be applied, and there will be different fields and rules. It would be a good choice if you could build a generic validation function that can be 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
Copy after login

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

13. Double-bit operators

Bit operators are the basic knowledge points in JavaScript beginner tutorials, but we don’t often use bit operators. Because no one wants to work with 1s and 0s without dealing with binary.

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

Math.floor(4.9) === 4  //true
Copy after login

The abbreviation is:

~~4.9 === 4  //true
Copy after login

The above is a complete introduction to the abbreviation techniques that JavaScript developers need to know (advanced), if you want to know more about JavaScript video tutorial, please pay attention to the PHP Chinese website.

The above is the detailed content of Shorthand tips that JavaScript developers need to know (advanced). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template