20 JS abbreviation skills to improve work efficiency

20 JS abbreviation skills to improve work efficiency

Preface:

Recently I read some articles on simplifying JS code. I think one of them is pretty good, but it is in English. I also read some Chinese translations. One of them is that the word-by-word translation is too stiff and does not become my own. The other is that the author has added new content but has not updated it in time. So I translated it into this article according to my own language. The characteristics of this article are mainly concise and concise.

When declaring multiple variables at the same time, you can shorten it to one line:

//Longhand
let x;
let y = 20;
 
//Shorthand
let x, y = 20;


Destructuring can be used to assign values ​​to multiple variables at the same time

//Longhand
let a, b, c;

a = 5;
b = 8;
c = 12;

//Shorthand
let [a, b, c] = [5, 8, 12];


Using the ternary operator to simplify if else

//Longhand 
let marks = 26; 
let result; 
if (marks >= 30) {
   result = 'Pass'; 
} else { 
   result = 'Fail'; 
} 

//Shorthand 
let result = marks >= 30 ? 'Pass' : 'Fail';


Use the || operator to assign default values ​​to variables

The essence is to use the characteristics of the || operator. When the result of the previous expression is converted to a Boolean value of false , the value is the result of the following expression.

//Longhand
let imagePath;

let path = getImagePath();

if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}

//Shorthand
let imagePath = getImagePath() || 'default.jpg';

Using the && operator to simplify if statements

For example, if a function is called only when a certain condition is true, it can be shortened to

//Longhand
if (isLoggedin) {
    goToHomepage();
 }

//Shorthand
isLoggedin && goToHomepage();


Using destructuring to swap the values ​​of two variables

let x = 'Hello', y = 55;

//Longhand
const temp = x;
x = y;
y = temp;

//Shorthand
[x, y] = [y, x];

Apply arrow functions to simplify functions

//Longhand
function add(num1, num2) {
  return num1 + num2;
}

//Shorthand
const add = (num1, num2) => num1 + num2;


Note the difference between arrow functions and normal functions

Simplify your code using string templates

Use template strings instead of raw string concatenation

//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);

//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);

Multi-line strings can also be simplified using string templates

//Longhand
console.log('JavaScript, often abbreviated as JS, is a\n' + 
            'programming language that conforms to the \n' + 
            'ECMAScript specification. JavaScript is high-level,\n' + 
            'Often just-in-time compiled, and multi-paradigm.'
            );


//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
            programming language that conforms to the
            ECMAScript specification. JavaScript is high-level,
            often just-in-time compiled, and multi-paradigm.`
            );


For multi-value matching, all values ​​can be placed in an array and simplified using array methods

//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
  // Execute some code
}

// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
   // Execute some code
}

// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // Execute some code 
}

Using the concise syntax of ES6 objects

For example: When the attribute name and variable name are the same, they can be abbreviated to one.

let firstname = 'Amitav';
let lastname = 'Mishra';

//Longhand
let obj = {firstname: firstname, lastname: lastname};

//Shorthand
let obj = {firstname, lastname};


Using unary operators to simplify string to number conversion

//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');

//Shorthand
let total = +'453';
let average = +'42.6';


Use the repeat() method to simplify repeating a string

//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
  str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello

// Shorthand
'Hello '.repeat(5);

// I want to say sorry to you 100 times!
'sorry\n'.repeat(100);


Use double asterisks instead of Math.pow()

//Longhand
const power = Math.pow(4, 3); // 64

// Shorthand
const power = 4**3; // 64


Use the double tilde operator (~~) instead of Math.floor()

//Longhand
const floor = Math.floor(6.8); // 6

// Shorthand
const floor = ~~6.8; // 6


Note that ~~ is only applicable to numbers less than 2147483647

Using the spread operator (...) to simplify code

Simplifying array merging

let arr1 = [20, 30];

//Longhand
let arr2 = arr1.concat([60, 80]); // [20, 30, 60, 80]

//Shorthand
let arr2 = [...arr1, 60, 80]; // [20, 30, 60, 80]


Copying a single layer object

let obj = {x: 20, y: {z: 30}};

//Longhand
const makeDeepClone = (obj) => {
  let newObject = {};
  Object.keys(obj).map(key => {
      if(typeof obj[key] === 'object'){
          newObject[key] = makeDeepClone(obj[key]);
      } else {
          newObject[key] = obj[key];
      }
});

return newObject;
}

const cloneObj = makeDeepClone(obj);



//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));

//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};

Finding the maximum and minimum values ​​in an array

// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2


Use for in and for of to simplify the ordinary for loop

let arr = [10, 20, 30, 40];

//Longhand
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

//Shorthand
//for of loop
for (const val of arr) {
  console.log(val);
}

//for in loop
for (const index in arr) {
  console.log(arr[index]);
}


Simplify getting a character in a string

let str = 'jscurious.com';

//Longhand
str.charAt(2); // c

//Shorthand
str[2]; // c


Removing Object Properties

let obj = {x: 45, y: 72, z: 68, p: 98};

// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}

// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}


Use arr.filter(Boolean) to filter out the value falsey of the array member

let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];

//Longhand
let filterArray = arr.filter(function(value) {
    if(value) return value;
});
// filterArray = [12, "xyz", -25, 0.5]

// Shorthand
let filterArray = arr.filter(Boolean);
// filterArray = [12, "xyz", -25, 0.5]

This concludes this article about 20 JS abbreviation tips to improve work efficiency. For more relevant JS abbreviation tips, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Share 5 JavaScript writing tips
  • Common JavaScript array operation skills (Part 2)
  • Common JavaScript array operation techniques
  • A practical guide to JavaScript destructuring assignment
  • Introduction and tips for using the interactive visualization JS library gojs
  • 3 Tips You Must Know When Learning JavaScript
  • Forty-nine JavaScript tips and tricks
  • Share 7 killer JS tips

<<:  Build a high-availability MySQL cluster with dual VIP

>>:  HTML table only displays the outer border of the table

Recommend

Detailed explanation of type protection in TypeScript

Table of contents Overview Type Assertions in syn...

Detailed explanation of the usage of two types of temporary tables in MySQL

External temporary tables A temporary table creat...

Sample code for a large drop-down menu implemented in pure CSS

This is a large drop-down menu implemented purely...

React encapsulates the global bullet box method

This article example shares the specific code of ...

How to load third-party component libraries on demand in Vue3

Preface Take Element Plus as an example to config...

JavaScript implements displaying a drop-down box when the mouse passes over it

This article shares the specific code of JavaScri...

Some data processing methods that may be commonly used in JS

Table of contents DOM processing Arrays method Su...

9 Practical CSS Properties Web Front-end Developers Must Know

1. Rounded Corners Today's web designs are con...

Use Xshell to connect to the Linux virtual machine on VMware (graphic steps)

Preface: I recently started to study the construc...

How to Delete Junk Files in Linux Elegantly

I wonder if you are like me, a programmer who arr...

Solve the problem of blocking positioning DDL in MySQL 5.7

In the previous article "MySQL table structu...

4 ways to optimize MySQL queries for millions of data

Table of contents 1. The reason why the limit is ...

Solution to the problem that MySQL commands cannot be entered in Chinese

Find the problem Recently, when I connected to th...