Shorthand tips for JavaScript developers to know

Source: Internet
Author: User

This article comes from years of experience in JavaScript coding techniques that are suitable for all developers who are programming with JavaScript.

The purpose of this article is to help you become more proficient in the use of JavaScript language for development work.

This article will be divided into two parts: primary and Advanced, respectively.

Beginner's article

1, trinocular operator

The following is a good example of a complete if statement, abbreviated 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 ': ' less than 10 ';

2. Circular statements

The following shorthand is 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)
The following is a shorthand example of traversing an array of 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. Declaring variables

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

Let X;
Let y;
Let z = 3;
can be abbreviated as:

Let x, Y, z=3;

4. If statement

You can omit the assignment operator when you use if for basic judgment.

if (Likejavascript = = = True)
Abbreviated as:

if (likejavascript)

5, decimal number

You can use scientific notation instead of larger data, such as 10000000 shorthand for 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 multiple lines of string in your code, 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 '
But there is an easier way to use only quotes:

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. Assigning values to variables

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

You can do this by writing a judgment statement that contains multiple conditions:

if (variable1!== null | | variable1!== undefined | | variable1!== ') {
Let variable2 = variable1;
}
or shorthand for 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, you do not need to write six lines of code to assign the default value. We can just use a short logical operator and do the same thing with just one line of code.

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 a very simple way to assign properties to an object. If the property name is the same as the key name, you can use shorthand.

Const OBJ = {x:x, y:y};
Abbreviated as:

Const OBJ = {x, y};

4. Arrow function

Classic functions are easy to read and write, but if they are nested in other functions, the whole function becomes somewhat verbose and confusing. You can use the arrow function to shorthand:

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

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

function calccircumference (diameter) {
return Math.PI * diameter
}
Abbreviated as:

calccircumference = diameter = = (
Math.PI * diameter;
)

6. Default parameter values

You can use the IF statement to define default values for function parameters. The ES6 specifies that default values can be defined in a function declaration.

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, but was there a simpler way?

ES6 provides the appropriate method, we can use the inverse quotation marks and $ {} to synthesize a variable into a string.

Const WELCOME = ' You had logged in as ' + First + ' + Last + '. '
Const DB = '/http ' + Host + ': ' + port + '/' + database;
Abbreviated as:

Const WELCOME = ' You had logged in as ${first} ${last} ';
Const DB = ' http://${host}:${port}/${database} ';

8. Deconstruction Assignment

An deconstruction assignment is an expression that quickly extracts a property value from an array or object and assigns it to a defined variable.

In the code shorthand aspect, the deconstruction assignment can achieve the very good result.

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. Expand operator

The expand operator is introduced in ES6, which makes JavaScript code more efficient and interesting by using the expand operator.

You can replace some array functions with the expand 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 () feature, a user can use an 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 expand 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}

10. Mandatory parameters

By default, if you do not pass a value to a function parameter, JavaScript sets the function parameter to undefined. Some other languages issue warnings or errors. To perform a parameter assignment, you can use an if statement to throw an undefined error, or you can take advantage of the force parameter.

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 have ever written the find function in normal JavaScript, you may have used a for loop. In ES6, a new array function called FIND () is introduced to implement 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 approach 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 perfectly completes the validation work. But when there are many forms, you need to apply validation, and there are different fields and rules. It is a good choice if you can build a generic validation function that is configured at run time.

Object validation Rules
Const schema =www.yunduanpingtai.cn {
First: {
Required:true
},
Last: {
Required:true
}
}

Universal Validation function
Const VALIDATE = (schema,www.huihuang178.cn 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 (www.lenlin88.cn 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.

13. Double-bit operator

Bit operators are a basic point of the JavaScript beginner's tutorial, but we don't often use bit operators. Because no one is willing to use 1 and 0 without processing the binary.

But the two-bit operator has a very practical case. You can use the double-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

JavaScript Development Tools Recommended

The Spreadjs pure front-end Table control is a HTML5-based JAVASCRIPT spreadsheet and Grid feature control that provides complete formula engine, sorting, filtering, input controls, data visualization, Excel Import/export, and more for. NET, Java and mobile terminal, such as online editing of Excel functions of the table program development.

Summarize

These are some commonly used JavaScript shorthand techniques, and if there are other shorthand techniques not mentioned, you are welcome to add them.

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

Shorthand tips for JavaScript developers to know

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.