[JS foundation] 16 elegant JavaScript shorthand skills

16 elegant JavaScript shorthand tips


Ternary operator

When you want to write if...else statements, use ternary operators instead

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

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


Short-circuit evaluation shorthand

When assigning another value to a variable, you want to make sure that the original value is not null, undefined or empty. You can write an if statement with multiple conditions

if(a !== null || a !== undefined || a !== '') {
    
    
  let b = a;
}

Or you can use the short-circuit evaluation method:const b = a || 'new'

Shorthand method of declaring variables

let x;
let y;
let z = 3;

Shorthand method: let x, y, z = 3

Shorthand method for if existence condition

if(a === true)

Shorthand: if(a)

The two sentences are equal only when a is true

If the judgment value is not true, you can do this:

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

Shorthand:

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

JavaScript loop shorthand method

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

Shorthand: for (let index in allImgs)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

Short circuit evaluation

To assign a value to a variable by judging whether its value is null or undefined, you can:

let dbHost;
if (process.env.DB_HOST) {
    
    
  dbHost = process.env.DB_HOST;
} else {
    
    
  dbHost = 'localhost';
}

Shorthand:const dbHost = process.env.DB_HOST || 'localhost'


Decimal Exponent

When you need to write a number with many zeros (such as 10000000), you can use an exponent (1e7) to replace this number: for (let i = 0; i < 10000; i++) {}abbreviated:

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

// 下面都是返回 true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

Object attribute shorthand

If the attribute name is the same as the key name, you can use the ES6 method:

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

Shorthand:const obj = { x, y }

Arrow function shorthand

Traditional function writing methods are easy for people to understand and write, but when nested in another function, these advantages are lost.

function sayHello(name) {
    
    
  console.log('Hello', name)
}

setTimeout(function() {
    
    
  console.log('Loaded')
}, 2000)

list.forEach(function (item) {
    
    
  console.log(item)
})

Shorthand:

sayHello = name => console.log('Hello', name)

setTimeout(() => console.log('Loaded'), 2000)

list.forEach(item => console.log(item))

Implicit return value shorthand

The return statement is often used to return the final result of a function. The arrow function of a single statement can implicitly return its value (the function must omit {} in order to omit the return keyword)

To return multi-line statements (such as object literal expressions), you need to use () to surround the function body.

function calcCircumference(diameter) {
    
    
  return Math.PI * diameter
}

var func = function func() {
    
    
  return {
    
     foo: 1 }
}

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter
)

var func = () => ({
    
     foo: 1 })


Default parameter value

In order to pass the default value to the parameter in the function, it is usually written by using the if statement, but using ES6 to define the default value, it will be very concise:

function volume(l, w, k) {
    
    
  if(w === undefined) 
    w = 3;
  if(h === undefined)
    k = 4;
  return l * w * k
}

Shorthand:

volume = (l, w = 3, k = 4) => (l * w * h);
volume(2) // 输出: 24

Template string

Traditional JavaScript language, the output template is usually written like this

const welcome = 'You have logged in as' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

ES6 can use backticks and the shorthand ${}:

const welcome = `You have logged in as ${
      
      first} ${
      
      last}`

const db = `http://${
      
      host}:${
      
      port}/${
      
      database}`;

Shorthand method for destructuring assignment

In web frameworks, it is often necessary to pass data in the form of arrays or objects back and forth between components and APIs, and then need to deconstruct it

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 also assign variable names:

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

Multi-line string shorthand

Need to output multi-line strings, you need to use + to splice:

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'

Using backticks, you can achieve a shorthand effect:

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.`

Shorthand for spread operator

There are several use cases for the spread operator to make JavaScript code more effective and can be used to replace an array function

// joining arrays
const odd = [1,3,5]
const nums = [2,4,6].concat(odd)

// cloning array
const arr = [1,2,3,4]
const arr2 = arr.slice()

Shorthand:

// 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 spread operator to insert another array anywhere in an array

const odd = [1,3,5]
const nums = [2,...odd,4,6]

You can also use spread operator destructuring:

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}

Shorthand for double non-bit operation

There is a valid use case for the double negation operator. Can be used instead of Math.floor(), its advantage is that it runs faster, you can read this article to learn more about bit operations

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

Shorthand:

~~4.9 === 4 // true

Guess you like

Origin blog.csdn.net/weixin_43352901/article/details/108712867
Recommended