For any JavaScript-based developer, this is definitely a must-read article, and an artifact that boosts development efficiency.
Body
Js
1. Ternary operators
Using the ternary operator is a good choice when you want to write If...else statements in one line of code, such as:
const x = 20;
Let answer;
if (x > 10) {
Answer = ' is greater ';
} else {
can be abbreviated as:
Const ANSWER = x > 10? ' is greater ': ' is lesser ';
1
1
You can also nest if statements:
Const BIG = x > 10? "Greater": X
1
1
2 Short-circuit evaluation
When assigning another value to a variable, you may want to determine whether the initial value is not null,undefined or null. At this point, you can write a multiple-condition if statement:
if (variable1!== null | | variable1!== undefined | | variable1!== ') {
Let variable2 = variable1;
Or you can use a short-circuit evaluation method:
Const VARIABLE2 = Variable1 | | ' New ';
1
1
3. Shorthand variable Declaration
When defining a function, you may want to declare multiple variables first, for example:
Let X;
Let y;
At this point, you can save a lot of time and space by using shorthand, which means declaring multiple variables at the same time:
Let x, Y, z=3;
1
1
4. Abbreviated if execution conditions
This may be insignificant, but it is worth mentioning. When you do an if condition check, the assignment operation can be omitted, for example:
if (Likejavascript = = = True)
1
1
can be abbreviated as:
if (likejavascript)
1
1
The above two statements can be replaced only if the Likejavascript is true. If you are judging false values, for example:
Let A;
if (a!== true) {
Do something ...
can be abbreviated as:
Let A;
if (!a) {
Do something ...
5. Shorthand JavaScript Loop method
This is useful when you want to use pure JavaScript without relying on external libraries (such as jquery).
for (Let i = 0; i < allimgs.length; i++)
1
1
can be abbreviated as:
For (let Index in Allimgs)
1
1
You can also use 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
6. Short-circuit evaluation
If you want to determine whether a parameter is null or undefined to assign a default value, we do not need to write six lines of code, but can use a short-circuit logical operator, only one line of code to complete the same operation. For example:
Let Dbhost;
if (Process.env.DB_HOST) {
Dbhost = Process.env.DB_HOST;
} else {
Dbhost = ' localhost ';
6
can be abbreviated as:
Const DBHOST = Process.env.DB_HOST |www.wmyl110.com| ' localhost ';
1
1
7. Decimal Index
When the tail of the number is a lot of 0 o'clock (such as 10000000), we can use the exponent (1e7) instead of the number, for example:
for (Let i = 0; i < 10000; i++) {}
1
1
can be abbreviated as:
for (Let i = 0; i < 1e7; i++) {}
The following are all returns True
1e0 = = = 1;
1E1 = = = 10;
1e2 = = = 100;
1e3 = = = 1000;
1e4 = = = 10000;
1e5 = = = 100000;
8. Shorthand Object Properties
Defining objects in JavaScript is simple, and ES6 provides a simpler way to assign object properties. If the property name is the same as the key value, for example:
Const OBJ = {x:x, y:y};
1
1
It can be abbreviated as:
Const OBJ = {x, y};
1
1
9. Shorthand arrow function
Traditional functions are easy to understand and write, but when nested within another function, it becomes verbose and confusing. For example:
function SayHello (name) {
Console.log (' Hello ', name);
}
SetTimeout (function () {
Console.log (' Loaded ')
}, 2000);
List.foreach (function (item) {
Console.log (item);
At this point, you can shorthand for:
SayHello = name = Console.log (' Hello ', name);
SetTimeout (() = Console.log (' Loaded '), 2000);
List.foreach (item = Console.log (item));
10. Shorthand implicit return value
We often use the return statement to return the final result of the function, and only one line of the arrow function that declares the statement can implicitly return its value (at which point the function must omit {} to omit the return keyword). If you want to return multiple lines of statement, you need to surround the function body with (). For example:
function calccircumference (diameter) {
return Math.PI * diameter
}
var func = function func () {
return {foo:1};
can be abbreviated as:
calccircumference = diameter = = (
Math.PI * diameter;
)
var func = () = ({foo:1});
11. Default parameter values
We can often use an if statement to define a default value for a parameter in a function. But in ES6, we can declare the default value of a parameter in the function itself. For example:
function Volume (l, W, h) {
if (w = = = undefined)
W = 3;
if (h = = = undefined)
h = 4;
Return L * w * H;
can be abbreviated as:
Volume = (l, W = 3, h = 4) =>www.chuangyed.com (L * w * h);
Volume (2)//output:24
12. String templates
Are you tired of using + to convert multiple variables to strings? Is there a simpler way? If you can use ES6, then fortunately, you just need to use the anti-quote and put the variable in ${}. For example:
Const WELCOME = ' You had logged in as ' + First + ' + Last + '. '
Const DB = '/http ' + Host + ': ' + port + '/' + database;
can be abbreviated as:
Const WELCOME = ' You had logged in as ${first} ${last} ';
Const DB = ' http://${host}:${port}/${database} ';
13. Shorthand Assignment method
If you are using any of the popular WEB frameworks, it is likely that you will use arrays or communicate the data between components and APIs in the form of an object article. Once the data object arrives at a component, you need to unzip it. For example:
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;
can be abbreviated as:
Import {observable, action, runinaction} from ' MOBX ';
const {store, form, loading, errors, entity} www.wmyl15.com/
3
You can also assign variable names:
The last variable is called contact
const {store, form, loading, errors, entity:contact} = this.props;
14. Shorthand multi-line string
If you've ever found yourself needing to write multiple lines of string in your code, this estimate is the way you write them, using a + to stitch between the multiple lines of output:
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 if you use anti-quotes, you can achieve the purpose of shorthand:
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. '
15. Extension operators
In ES6, including the extension operator, it can make your operation simpler, for example:
Joining arrays
Const ODD = [1, 3, 5];
Const NUMS = [2, 4, 6].www.wmyl119.cn concat (odd);
Cloning arrays
Const ARR = [1, 2, 3, 4];
Const ARR2 = Arr.slice ()
can be 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 () function, you can use an extension operator to insert another array anywhere in an array, for example:
Const ODD = [1, 3, 5];
Const NUMS = [2, ... odd, 4, 6];
You can also use the extension operator:
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}
16. Mandatory parameters
By default, if you do not pass a value, JavaScript sets the function argument to undefined, while some other languages report a warning or error. If you want to perform a parameter assignment, you can let the if statement throw a undefined error, or use the "force arguments" method. For example:
function foo (bar) {
if (bar = = = undefined) {
throw new Error (' Missing www.wmyl11.com parameter! ');
}
return bar;
can be abbreviated as:
Mandatory = () + = {
throw new Error (' Missing www.zbcppt.com parameter! ');
}
Foo = (bar = mandatory ()) = = {
Array.find Shorthand
If you've ever been responsible for writing the Find function in JavaScript, you're probably using a for loop. Here, an array function named Find () is introduced in ES6.
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];
can be abbreviated as:
Pet = pets.find (Pet = Pet.type = = = ' Dog ' && pet.name = = = ' Tommy ');
Console.log (PET); {type: ' Dog ', Name: ' Tommy '}
1
2
1
2
18. Abbreviated Object[key]
Do you know that Foo.bar can also be written as foo[' bar '? At first, there seems to be no reason for you to write like this. However, this symbol gives you the basis for writing reusable code. Consider the following simplified validation function example:
function validate (values) {
if (!values.first)
return false;
if (!values.last)
return false;
return true;
}
Console.log (Validate ({first: ' Bruce ', Last: ' Wayne '}); True
This function can complete its task perfectly. However, consider a scenario where you have many forms that you need to validate, but have different fields and rules. So, isn't it nice to build a generic validation function that can be configured at run time?
Object validation Rules
Const SCHEMA = {
First: {
Required:true
},
Last: {
Required:true
}
}
Universal Validation Functions
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 we have a validation function that can be reused in all the form, without having to write its own custom validation function for each form!
19. Shorthand Dual bitwise non-operator
The bitwise operator is definitely the operator you know when you first learn JavaScript, but that has never been useful. Because if the binary is not processed, who will have nothing to do with 0 and 1? However, a double bitwise non-operator is useful, for example you can use it instead of the floor () function, and the bitwise operator operates faster than other identical operations.
Math.floor (4.9) = = = 4//true
1
1
can be abbreviated as:
~~4.9 = = = 4//true
Suggest One of U?
I like these shorthand methods, but also hope to find more shorthand methods, if you know, please leave a message here, thank you very much!
Translation statement: This article originates from "sitepoint",19+ JavaScript shorthand Coding techniques.
Common shorthand techniques for 19+ JavaScript