JavaScript coding tips sharing

  • 2021-08-21 19:39:59
  • OfStack

3-ary operator

If you use the if... else statement, this is a good way to save code.


const x = 20;
let big;
if (x > 10) {
big = true;
} else {
big = false;
}
// Write like this ...
const big = x > 10 ? true : false;

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 null. You can write a conditional statement with multiple if or Short-circuit Evaluation.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';

Don't trust me, trust your own tests first (you can paste the following code in es6console)


let variable1;
let variable2 = variable1 || '';
console.log(variable2 === ''); // true
variable1 = 'foo';
variable2 = variable1 || '';
console.log(variable2); // foo

Declare variables

When declaring variables in a function, declaring multiple variables at the same time like the following can save you a lot of time and space:


let x;
let y;
let x = 3;

// or 
let x, y, z = 3;

If it exists

This may be trivial, but it is worth mentioning. When doing "if check", the assignment operator can sometimes be omitted.


if (likeJavaScript === true)
//or
if (likeJavaScript)

Note: These two methods are not identical, and the abbreviation check will pass as long as likeJavaScript is true.

Here is another example. If a is not true, then what to do.


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

for Cycle of JavaScript

This tip is useful if you only want native JavaScript and don't want to rely on external libraries such as jQuery or Lodash.


for (let i = 0; i < allImgs.length; i++)
//or
for (let index in allImgs)

Array. forEach Abbreviation:


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

Object properties

Defining object text (Object literals) makes JavaScript more interesting. ES 6 provides a simpler way to assign attributes to objects. If the attribute name and value are the same, you can use the following abbreviation.


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

Arrow function

Classical functions are easy to read and write, but they do get a little verbose, especially when you call other functions in nested functions.


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

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

Implicit return

return in the function often used in a keyword, will return the final result of the function. The arrow function returns the result implicitly in a single statement (the function must omit {} in order to omit the return keyword).

If you return a multiline statement (such as an object), it is necessary to use () instead of {} in the function body. This ensures that the code is returned as a separate statement.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
0

Default parameter value

You can use the if statement to define the default values of function parameters. In ES6, default values can be defined in function declarations.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
1

Template Literals (String Template)

Are you tired of using + to concatenate multiple variables into a string? Isn't there an easier way? If you can use ES6, then you are lucky. In ES 6, all you have to do is use apostrophes and ${}, and put your variables in curly braces.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
2

Destructuring Assignment (Deconstruction Assignment)


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;

//or

import {observable, action, runInAction} from 'mobx';
const {store, form, loading, errors, entity} = this.props;

You can even specify your own variable name:


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
4

Spread Operator (Extension Operator)

Spread Operator was introduced in ES 6 to make the JavaScript code more efficient and interesting. It can be used to replace some array functions. Spread Operator is just a series of 3 dots (...).


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
5

Unlike the concat () function, with Spread Operator you can insert one array anywhere in another array.


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
6

It can also be used as a deconstructor:


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
7

Forced parameter


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

Array.find

If you have written a lookup function before, you may use an for loop. In ES 6, you can use a new feature of arrays, find ().


if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
  let variable2 = variable1;
}
//  Write like this 
const variable2 = variable1 || 'new';
9

Object[key]

You know Foo. bar can also be written as Foo [bar]. At first, there seems to be no reason to write like this. However, this symbol allows you to write reusable code blocks.


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 works properly. However, one scenario needs to be considered: There are many forms of validation that need to be applied, and there are different rules in different domains. It is difficult to create a general authentication function at runtime.


// object validation rules
const schema = {
first: {
required: true
  },
last: {
required: true
  }
}
// universal validation 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

We now have a validation function, which can be reused in various forms without having to customize a validation function for each different function.

Double Bitwise NOT

If you are new to the 1-bit JavaScript, you should never use the bit-by-bit operator (Bitwise Operator) anywhere. In addition, if you don't deal with binary zeros and ones, you won't want to use them.

However, one very practical use case is the two-bit operator. You can use it instead of Math. floor (). The Double Bitwise NOT operator has the great advantage of performing the same operation much faster. You can read more about bit operators here.


Math.floor(4.9) === 4; // true
//or
~~4.9 === 4; //true

The above is JavaScript coding tips to share the details, more information about JavaScript coding skills please pay attention to other related articles on this site!


Related articles: