The shorthand for JavaScript developers

Source: Internet
Author: User

The shorthand for JavaScript developers

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

The purpose of this article is to help you more skillfully use the JavaScript language for development.

The article will be divided into two parts: the preliminary article and the advanced article.

 

Preliminary Article 1. Three-object Operators

The following is a good example. A complete if statement is abbreviated as a line of code.

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

Abbreviated:

const answer = x > 10 ? 'greater than 10' : 'less than 10';
2. Loop statements

The following shorthand is useful when using pure JavaScript (not dependent on external libraries, such as jQuery or lodash.

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

Abbreviated:

for (let index of allImgs)

The 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

Before the function starts, assigning values to variables is a good habit. When declaring multiple variables:

let x;let y;let z = 3;

Can be abbreviated:

let x, y, z=3;

 

4. if statement

When using if for basic judgment, you can omit the value assignment operator.

if (likeJavaScript === true)

Abbreviated:

if (likeJavaScript)

 

5. decimal number

Scientific notation can be used to replace large data. For example, 10000000 can be abbreviated as 1e7.

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

Abbreviated:

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

 

6. Multi-line string

If you need to write multiple lines of strings in the code, as shown below:

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'

However, there is a simpler way to use only the quotation marks:

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

 

Advanced Article 1. Variable assignment

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

You can write a judgment statement that contains multiple conditions:

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

Or, in the following format:

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 truevariable1 = 'foo';variable2 = variable1  || '';console.log(variable2); // prints foo

 

2. Default Value assignment

If the expected parameter is null or undefined, you do not need to write six lines of code to assign the default value. We can use only one short logical operator to perform the same operation with only one line of code.

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

Abbreviated:

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

 

3. Object Attributes

ES6 provides a simple way to allocate attribute objects. If the attribute name is the same as the key name, you can use the abbreviation.

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

Abbreviated:

const obj = { x, y };

 

4. Arrow Functions

Classic functions are easy to read and write, but if they are nested in other functions for calling, the entire function will become lengthy and messy. At this time, you can use the arrow function to Abbreviation:

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

Abbreviated:

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 that we usually use to return the final result of the function. Only the arrow function of one statement can return results implicitly (the function must omit parentheses ({}) to omit the return keyword ).

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

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

Abbreviated:

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

 

6. default parameter values

You can use the if statement to define the default values of function parameters. ES6 specifies that the default value can be defined in the function declaration.

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

Abbreviated:

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 the corresponding method. We can use reverse quotation marks and $ {} to synthesize a variable into a string.

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

Abbreviated:

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

 

8. Deconstruct assignment

Deconstruct value assignment is an expression used to quickly extract attribute values from arrays or objects and assign them to Defined variables.

In terms of code shorthand, deconstruct value 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:

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

The expansion operator is introduced in es6. using the expansion operator makes JavaScript code more effective and interesting.

You can use the expansion operator to replace some array functions.

// joining arraysconst odd = [1, 3, 5];const nums = [2 ,4 , 6].concat(odd); // cloning arraysconst arr = [1, 2, 3, 4];const arr2 = arr.slice( )

Abbreviated:

// joining arraysconst odd = [1, 3, 5 ];const nums = [2 ,4 , 6, ...odd];console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arraysconst arr = [1, 2, 3, 4];const arr2 = [...arr];

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

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

You can also use the expansion operator and ES6 deconstruct:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };console.log(a) // 1console.log(b) // 2console.log(z) // { c: 3, d: 4 }

 

10. Mandatory Parameters

By default, if you do not pass a value to a function parameter, JavaScript sets the function parameter to undefined. Other languages may issue warnings or errors. To execute parameter allocation, you can use the if statement to throw an undefined error, or use "force parameter ".

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

Abbreviated:

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

 

11. Array. find

If you have written the find function in common JavaScript, you may have used the for loop. ES6 introduces a new array function named find (), which can be abbreviated as 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:

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

 

12. Object [key]

Although writing foo. bar as foo ['bar'] is a common practice, this practice forms the basis for writing reusable code.

Consider the following simplified example of the 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

The above function completes the verification work perfectly. However, if there are many forms, you need to apply the verification. Different fields and Rules are available. If you can build a universal verification function configured at runtime, it will be a good choice.

// object validation rulesconst schema = {  first: {    required:true  },  last: {    required:true  }} // universal validation functionconst validate = (schema, values) => {  for(field in schema) {    if(schema[field].required) {      if(!values[field]) {        return false;      }    }  }  return true;}console.log(validate(schema, {first:'Bruce'})); // falseconsole.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

With this verification function, we can reuse it in all forms without writing custom verification functions for each form.

 

13. bitwise operators

Bitwise operators are the basic knowledge points in JavaScript beginners, but we do not often use bitwise operators. Because no one is willing to use 1 and 0 without processing binary data.

However, the double-bit operator has a very practical case. You can use the double-bit operator to replace Math. floor (). The advantage of the double negative bitwise operator is that it performs the same operation faster.

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

Abbreviated:

~~4.9 === 4  //true

 

JavaScript development tool recommendation

SpreadJS pure front-end table control is a JavaScript spreadsheet and grid Function Control Based on HTML5. It provides complete functions such as formula engine, sorting, filtering, input control, data visualization, and Excel import/export, applicable.. NET, Java, and mobile platforms.

 

Summary

These are some common JavaScript shorthand skills. If you have other shorthand skills that are not mentioned, you are welcome to add them.

Link: https://www.sitepoint.com/shorthand-javascript-techniques/

For more information, see grape city control.

 

About grape City

Founded in 1980, grape City is the world's largest provider of controls and a world-leading provider of enterprise application customization tools, enterprise reports, and business intelligence solutions, it provides services to Fortune 75% enterprises in more than 500. Grape city set up a R & D center in China in 1988. During the R & D process of global products, it constantly adapts to the local needs of the Chinese market, it also provides excellent software tools and consulting services for software enterprises and informatization in various industries.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.