Summary of several common ways to abbreviate javascript code

Summary of several common ways to abbreviate javascript code

Preface

This article mainly introduces some JavaScript coding skills commonly used in work. Very useful, I suggest you practice it right after reading it, keep it in your mind!

First, I would like to recommend a vscode plugin, Quokka.js, a code debugging tool. The function of the plugin is to immediately execute the JavaScript code or TypeScript code you type

Arrow Functions

Shorthand rules:

  1. There is only one parameter, the parentheses can be omitted
  2. There is only one return value, so curly braces and return can be omitted.
let arr = [1,2,3]

arr.filter((item)=>{
    return item >1
})

//There is only one parameter, the parentheses can be omitted arr.filter(item=>{
    return item>1
})
//There is only one return value, curly braces and return can be omitted arr.filter(item=>item>1)

Master common array operations

Master the common array methods and keep them in mind. Don't look at the API when writing. This can effectively improve coding efficiency. After all, these methods are used every day.

  • every
  • some
  • filter
  • map
  • forEach
  • find
  • findIndex
  • reduce
  • includes

Master the common string operation functions

  • trim
  • startsWidth
  • includes
let str="Hello JueJue "
//Contains substring console.log(str.includes("Hello"))
// Starts with a substring console.log(str.startsWith("Hello"))
// Remove trailing spaces console.log(str.trim())

Spread Operator

Very useful, here are two usage scenarios:

Destructuring an array

//Array deduplication function removeRepeat(arr){
    return [...new Set(arr)]
}
// Array maximum value Math.max(...arr)
Math.min(...arr)

Deconstructing an object

//react is used to pass multiple properties at once let props={name:'Ben',age:10,sex:0}
const greeting = <Greeting {...props} />

//Combined objects can use Object.assign instead of let defaultParams={
    pageSize:1,
    pageNumber:10,
    sort:1
}

let reqParams = {
    ...defaultParams,
    phone:'15196255885'
}

Object Shorthand

The key and value of the object have the same name, so you can just write the key, which can save a lot of code

let id,age,sex

let person={
    id,
    age,
    sex
}

Destructuring assignment

  • For function parameters
  • To deconstruct an object

Can you use less code?

class Spirit{
    constructor({x=0,y=0,w=10,h=10,rotate=0}){//Function parameter structure this.x=x
        this.y=y
        this.w=w
        this.h=h
        this.rotate=rotate
    }
    draw(){
        const {x,y,w,h,rotate}=this
        console.log("draw -> x,y,w,h,rotate", x,y,w,h,rotate)
    }
}

Master the methods of data type conversion

People who write JS generally have no type concept and are not very sensitive to the distinction between Number and String. In fact, the data type of JS is still very important. If you don't pay attention, you may make mistakes, so I hope everyone remembers the following method

Conversion between Number and String types

I generally like to use the constructor

Number('001') //-> 1
String('1') // ->1

Keep n decimal places

function cutNumber(value,n=2){//Default retains 2 decimal places return Number(value).toFixed(n)
}

Summarize

This is the end of this article about javascript code abbreviations. For more relevant javascript code abbreviations, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of custom swiper component in JavaScript
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • Implementing carousel effects with JavaScript
  • javascript to switch pictures by clicking a button
  • Summary of various methods for JavaScript to determine whether it is an array
  • JavaScript to achieve fireworks effects (object-oriented)
  • JavaScript Canvas implements Tic-Tac-Toe game
  • Detailed discussion of the differences between loops in JavaScript
  • 13 JavaScript one-liners that will make you look like an expert

<<:  How to change the MySQL database directory location under Linux (CentOS) system

>>:  Example of how to quickly build a Redis cluster with Docker

Recommend

Mysql error: Too many connections solution

MySQL database too many connections This error ob...

A brief discussion on whether MySQL can have a function similar to Oracle's nvl

Use ifnull instead of isnull isnull is used to de...

Detailed explanation of several solutions for JavaScript interruption requests

Table of contents 1 Promise Interrupt the call ch...

Ubuntu 20.04 Chinese input method installation steps

This article installs Google Input Method. In fac...

React diff algorithm source code analysis

Table of contents Single Node Diff reconcileSingl...

Problems encountered when updating the auto-increment primary key id in Mysql

Table of contents Why update the auto-increment i...

How to remotely connect to the cloud server database using Navicat

It is very convenient to connect to a remote serv...

htm beginner notes (must read for beginners)

1. What is HTML HTML (HyperText Markup Language):...

Summary of some tips on MySQL index knowledge

Table of contents 1. Basic knowledge of indexing ...

A summary of some of the places where I spent time on TypeScript

Record some of the places where you spent time on...

Nginx restricts IP access to certain pages

1. To prohibit all IP addresses from accessing th...

How to solve the error of PyCurl under Linux

Solution to "Could not run curl-config"...

ffmpeg Chinese parameter description and usage examples

1. When ffmpeg pushes video files, the encoding f...

Vue imitates ElementUI's form example code

Implementation requirements The form imitating El...