How to improve your javascript code

  javascript

ternary operator

When you want to use a line of code to write if…else statements, using the boolean-exp character is a very good choice, for example:

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

Can be abbreviated as:

const answer = x > 10 ?   'is greater' : 'is lesser';

You can also nest if statements:

const big = x > 10 ?  " greater 10" : x

Short circuit evaluation

When assigning another value to a variable, you may want to make sure that the initial value is not null, undefined, or null. At this time, you can write an if statement with multiple conditions:

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

Alternatively, a short-circuit evaluation method can be used:

const variable2 = variable1  || 'new';

Abbreviated variable declaration

When defining a function, you may need to declare multiple variables first, for example:

let x;
 let y;
 let z = 3;

In this case, you can save a lot of time and space by using the shorthand method, that is, declaring multiple variables at the same time:

let x, y, z=3;

Abbreviation if execution condition

This may be trivial, but it is worth mentioning. When you check the if condition, its assignment operation can be omitted, for example:

if (likeJavaScript === true)

Can be abbreviated as:

if (likeJavaScript)

The above two statements can be replaced only when the likeJavaScript is true. If a false value is determined, for example:

let a;
 if ( a !  == true ) {
 // do something  ...
 }

Can be abbreviated as:

let a;
 if ( !  a ) {
 // do something  ...
 }

Short JavaScript Loop Method

This is useful when you want to use pure javascript instead of relying on external libraries such as jQuery.

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

Can be abbreviated as:

for (let index in allImgs)

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

short circuit evaluation

If we want to assign the default value by judging whether the parameter is null or undefined, we do not need to write six lines of code, but we can use a short-circuit logic operator and use 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';
 }

Can be abbreviated as:

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

Decimal index

When the end of a number is many zeros (such as 10000000), we can use index (1e7) to replace the number, for example:

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

Can be abbreviated as:

for (let i = 0;   i < 1e7;  i++) {}
 
 
 //return true below
 1e0 === 1;
 1e1 === 10;
 1e2 === 100;
 1e3 === 1000;
 1e4 === 10000;
 1e5 === 100000;

Abbreviated object properties

Defining objects in JavaScript is simple, and ES6 provides a simpler way to assign object attributes. If the attribute name is the same as the key value, for example:

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

It can be abbreviated as:

const obj = { x, y };

Abbreviated arrow function

Traditional functions are easy to understand and write, but when nested in another function, it becomes tedious 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 time, it can be abbreviated as:

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

Abbreviation implicit return value

We often use the return statement to return the final result of the function. only the arrow function with one line of declaration statement can implicitly return its value (in this case, the function must omit {} to omit the return keyword). If you want to return a multiline 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 });

Default parameter value

We can often use if statements to define default values for parameters in functions. But in ES6, we can declare the default value of the 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 ) => (l * w * h);
 
 volume(2)   // output: 24

String template

Are you tired of using+to convert multiple variables into strings? Is there a simpler way? If you can use ES6, then luckily, you only need to use reverse quotation marks and put the variable in $ {}. For example:

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

Can be abbreviated as:

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

Abbreviation assignment method

If you are using any popular Web framework, you are likely to use arrays or communicate data between components and API in the form of object text. Once the data object reaches a component, you need to decompress 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 } = this.props;

You can also assign variable names:

//The last variable is named contact

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

Short for multi-line string

If you have ever found that you need to write multi-line strings in your code, then this is probably how you write them, that is, use+to splice between the output multi-line strings:

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 reverse quotation marks, 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.`

Extension operator

In ES6, including extension operators, it can make your operation simpler, such as:

// 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()

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 the 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 extension operators:

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 }

Mandatory parameter

By default, if no value is passed, JavaScript will set the function parameter to undefined, while other languages will report warnings or errors. If you want to perform parameter allocation, you can either have the if statement throw an undefined error or use the “force parameter” method. For example:

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

Can be abbreviated as:

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

Find shorthand

If you were responsible for writing the find function in JavaScript, you probably used the for loop. Here, an array function named find () in ES6 is introduced.

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' }

Abbreviation 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 to write reusable code. Consider the following simplified verification 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 and you need to verify them, but there are different fields and rules. So, isn’t it good to build a universal verification function that can be configured at run time?

//Object Verification Rules
 const schema = {
 first: {
 required:true
 },
 last: {
 required:true
 }
 }
 
 //Universal Verification 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
 Now we have a verification function that can be reused in all forms without writing its own custom verification function for each form!

Abbreviation Double Bitwise Nonoperator

Bitwise operators are definitely operators you knew when you started JavaScript, but they have never been used. Because if you don’t deal with binaries, who will have nothing to do with 0 and 1? However, the double bitwise non-operator is very practical. For example, you can use it to replace the floor () function, and the bitwise operator operates faster than other similar operations.

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

Can be abbreviated as:

~~4.9 === 4  //true

Suggest One of U?

These are all the contents of this article. I hope the contents of this article can bring some help to everyone’s study or work.