This article is suitable for any JavaScript-based developer. I wrote this article mainly on some shorthand code in JavaScript to help you better understand some of the basics of JavaScript. Hopefully the code will help you understand JavaScript from a different perspective.
Ternary operator
If you use if...else
a statement, this is a good way to save code.
Longhand:
Const x = 20;let big;if (x > Ten) { big = true;} else { big = false;}
Shorthand:
Const BIG = x > 10? True:false;
You can also nest statements like this if
:
Const BIG = x > 10? ' Greater ': X < 5? ' Less 5 ': ' Between 5 and 10 ';
Short-circuit Evaluation
When assigning a variable value to another variable, you may want to make sure that the variable is not null
, undefined
or is empty. You can write a multiple if
conditional statement or short-circuit Evaluation.
Longhand:
if (variable1!== null | | variable1!== undefined | | variable1!== ") {let variable2 = variable1;}
Shorthand:
Const VARIABLE2 = Variable1 | | ' New ';
Don't trust me, please trust your own test (you can paste the following code in Es6console)
Let Variable1;let variable2 = Variable1 | | "; Console.log (variable2 = = = ="); truevariable1 = ' foo '; variable2 = Variable1 | | "; Console.log (Variable2); Foo
declaring variables
When declaring a variable in a function, declaring multiple variables at the same time can save you a lot of time and space:
Longhand:
Let X;let y;let x = 3;
Shorthand:
Let x, y, z = 3;
If there is
This may be insignificant, but it is worth mentioning. Assignment operators can sometimes be omitted when doing a "if check".
Longhand:
if (Likejavascript = = = True)
Shorthand:
if (likejavascript)
Note: the two methods are not exactly the same, as long as the shorthand check likeJavaScript
true
will pass.
Here is another example. If a
not true
, then do what.
Longhand:
Let A;if (a!== true) { //do something ...}
Shorthand:
Let A;if (!a) { //do something ...}
JavaScript for Loop
This tip is useful if you want only native JavaScript and don't want to rely on external libraries such as jquery or Lodash.
Longhand:
for (Let i = 0; i < allimgs.length; i++)
Shorthand:
For (let Index in Allimgs)
Array.forEach
Shorthand:
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
Short-circuit Evaluation
If the argument is null
or is undefined
, we can simply use a short-circuit logical operation to implement a line of code instead of six lines of code.
Longhand:
Let Dbhost;if (Process.env.DB_HOST) { dbhost = Process.env.DB_HOST;} else { dbhost = ' localhost ';}
Shorthand:
Const Dbhost = Process.env.DB_HOST | | ' localhost ';
Decimal index
You may have seen this. It is essentially a strange way to write numbers, which is that there are many behind a number 0
. For example 1e7
10000000
, essentially the equivalent ( 1
there is 7
a later one 0
). It represents the decimal count equals 10000000
.
Longhand:
for (Let i = 0; i < 10000; i++) {}
Shorthand:
for (Let i = 0; i < 1e7; i++) {}//All the below would evaluate to true1e0 = = = 1;1e1 = = = 10;1e2 = = = 100;1e3 = = = 10000;1e5 = = 100000;
Object Properties
Defining object Literals (literals) makes JavaScript more interesting. ES6 provides an easier way to assign properties to objects. If the property name and value are the same, you can use the following shorthand method.
Longhand:
Const OBJ = {x:x, y:y};
Shorthand:
Const OBJ = {x, y};
Arrow functions
Classic functions are easy to read and write, but they do get a bit verbose, especially if you're confused when calling other functions in a nested function.
Longhand:
function SayHello (name) { console.log (' Hello ', name);} SetTimeout (function () { console.log (' Loaded ')}, + List.foreach (function (item) { Console.log (item)})
Shorthand:
SayHello = name = Console.log (' Hello ', name), SetTimeout (() = Console.log (' Loaded '), and list.foreach (item = > Console.log (item));
Implicit return
return
A keyword that is frequently used in a function returns the final result of the function. The arrow function uses a statement to return the result implicitly (the function must be omitted {}
, in order to omit the return
keyword).
If you return a multiline statement (such as an object), it is necessary to use overrides within the function body ()
{}
. This ensures that the code is returned as a separate statement.
Longhand:
function calccircumference (diameter) { return Math.PI * diameter}
Shorthand:
calccircumference = diameter = ( Math.PI * diameter;)
Default parameter values
You can use if
statements to define default values for function parameters. In ES6, you can define a default value in a function declaration.
Longhand:
function Volume (l, W, h) { if (w = = = undefined) w = 3; if (h = = = undefined) h = 4; Return L * w * H;}
Shorthand:
Volume = (l, W = 3, h = 4) = = (L * w * h); volume (2); 24
Template literals
Are you tired of using +
to concatenate multiple variables into a string? Isn't there an easier way to do it? If you can use ES6, then you are lucky. In ES6, all you have to do is use apostrophes and put ${}
your variables inside curly braces.
Longhand:
Const WELCOME = ' You had logged in as ' + First + ' + Last + '. Const DB = '/http ' + Host + ': ' + port + '/' + database;
Shorthand:
Const WELCOME = ' You had logged in as ${first} ${last} '; const DB = ' http://${host}:${port}/${database} ';
Destructuring Assignment
If you are using any of the popular web frameworks, there are many opportunities to use the form of arrays or data objects to pass information between the APIs. Once a data object reaches a single component, you need to expand it.
Longhand:
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;
Shorthand:
Import {observable, action, runinaction} from ' MOBX '; const {store, form, loading, errors, entity} = This.props;
You can even specify the variable name yourself:
const {store, form, loading, errors, entity:contact} = this.props;
Multi-line string
You'll find that the code that used to write the multiline string yourself would look like this:
Longhand:
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 c Onsequat. Duis aute\n\t ' + ' irure dolor in Reprehenderit in voluptate velit esse.\n\t '
But there is one more simple way. Use apostrophes.
Shorthand:
Const LOREM = ' Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut Labor E 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. '
Spread Operator
Spread Operator is introduced in ES6, making JavaScript code more efficient and interesting. It can be used instead of some array functions. Spread operator is just a series of three dots ( ...
).
Longhand:
Joining arraysconst odd = [1, 3, 5];const nums = [2, 4, 6].concat (odd);//cloning arraysconst arr = [1, 2, 3, 4];const ARR2 = Arr.slice ();
Shorthand:
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 concat()
functions, you can use spread operator to insert an array anywhere in another array.
Const ODD = [1, 3, 5];const nums = [2, ... odd, 4, 6];
Alternatively, it can be used as a destructor:
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}
Mandatory parameters
By default, JavaScript will be one if it does not pass a value to the function parameter undefined
. Some languages will also throw a warning or error. When executing a parameter assignment, you can use if
a statement that throws an error if undefined, or you can use the force parameter (Mandatory parameter).
Longhand:
function foo (bar) { if (bar = = = undefined) { throw new Error (' Missing parameter! '); } return bar;}
Shorthand:
Mandatory = () = { throw new Error (' Missing parameter! ');} Foo = (bar = mandatory ()) = = { return bar;}
Array.find
If you have previously written a lookup function, you may be using a for
loop. In ES6, you can use a new feature of the array find()
.
Longhand:
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];}}}
Shorthand:
Pet = pets.find (Pet = Pet.type = = = ' Dog ' && pet.name = = = ' Tommy '); Console.log (PET); {type: ' Dog ', Name: ' Tommy '}
Object[key]
You know Foo.bar
, you can write Foo[bar]
it. At first, there seems to be no reason to write like this. However, this symbol allows you to write reusable blocks of code.
Here is an example of a simplified function:
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 will work correctly. However, one scenario needs to be considered: there are many forms that require application validation, and different areas have different rules. It is difficult to create a common validation feature at run time.
Shorthand:
Object Validation Rulesconst schema = {First : { required:true }, last : { required:true }}//Universal Validation Functionconst validate = (schema, values) = = ( field in schema) { if (schema[fi eld].required) { if (!values[field]) { return false; } } } return true;} Console.log (Validate (schema, {first: ' Bruce '})); Falseconsole.log (Validate (schema, {first: ' Bruce ', Last: ' Wayne ')); True
Now we have a validation function that can be reused in various forms without having to customize a validation function for each of the different functions.
Double Bitwise not
If you are a novice JavaScript, you should never use the bitwise-Bitwise operator (Bitwise Operator) anywhere. In addition, if you do not deal with binary 0
and, you will 1
not want to use it.
However, a very useful use case, that is, a double-bit operator. You can use it instead Math.floor()
. The double Bitwise Not operator has a great advantage in that it performs the same operation much faster. You can read more about bit operators here.
Longhand:
Math.floor (4.9) = = = 4; True
Shorthand:
~~4.9 = = 4; True
Original: http://www.w3cplus.com/javascript/19-shorthand-javascript-techniques.html©w3cplus.com
19 JavaScript Simplified Coding Tips