10 great JavaScript shorthand skills

Posted by jadebabe on Sat, 26 Feb 2022 12:07:33 +0100

Today I want to share 10 great JavaScript shorthand methods, which can speed up the development speed and get twice the result with half the effort.

Let's go!

1. Merge arrays

Common writing:

We usually use the concat() method in Array to combine two arrays. Using the concat() method to merge two or more arrays does not change the existing Array, but returns a new Array. Take a simple example:

let apples = ['??', '??'];
let fruits = ['??', '??', '??'].concat(apples);

console.log( fruits );
//=> ["??", "??", "??", "??", "??"]

Abbreviation:

We can extend the operator (...) by using ES6 To reduce the code, as follows:

let apples = ['??', '??'];
let fruits = ['??', '??', '??', ...apples];  // <-- here

console.log( fruits );
//=> ["??", "??", "??", "??", "??"]

The output obtained is the same as that in normal writing.

2. Merge arrays (at the beginning)

Common writing:

Suppose we want to add all the items in the apples array to the beginning of the Fruits array instead of at the end as in the previous example. We can use array prototype. Unshift() to do this:

let apples = ['??', '??'];
let fruits = ['??', '??', '??'];

// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)

console.log( fruits );
//=> ["??", "??", "??", "??", "??"]

Now the red and green apples will merge at the beginning, not at the end.

Abbreviation:

We can still use the ES6 extension operator (...) Shorten this long code as follows:

let apples = ['??', '??'];
let fruits = [...apples, '??', '??', '??'];  // <-- here

console.log( fruits );
//=> ["??", "??", "??", "??", "??"]

3. Clone array

Common writing:

We can easily clone arrays by using slice() method in Array, as shown below:

let fruits = ['??', '??', '??', '??'];
let cloneFruits = fruits.slice();

console.log( cloneFruits );
//=> ["??", "??", "??", "??"]

Abbreviation:

We can use the ES6 extension operator (...) Clone an array like this:

let fruits = ['??', '??', '??', '??'];
let cloneFruits = [...fruits];  // <-- here

console.log( cloneFruits );
//=> ["??", "??", "??", "??"]

4. Deconstruction assignment

Common writing:

When processing arrays, we sometimes need to unpack the array into a pile of variables, as shown below:

let apples = ['??', '??'];
let redApple = apples[0];
let greenApple = apples[1];

console.log( redApple );    //=> ??
console.log( greenApple );  //=> ??

Abbreviation:

We can achieve the same result with one line of code by deconstructing the assignment:

let apples = ['??', '??'];
let [redApple, greenApple] = apples;  // <-- here

console.log( redApple );    //=> ??
console.log( greenApple );  //=> ??

5. Literal quantity of formwork

Common writing:

Usually, when we have to add an expression to a string, we do this:

// Display name in between two strings
let name = 'Palash';
console.log('Hello, ' + name + '!');
//=> Hello, Palash!

// Add & Subtract two numbers
let num1 = 20;
let num2 = 10;
console.log('Sum = ' + (num1 + num2) + ' and Subtract = ' + (num1 - num2));
//=> Sum = 30 and Subtract = 10

Abbreviation:

Through template literals, we can use backquotes (), so that we can wrap the expression in ${...} ` and embed it into the string, as shown below:

// Display name in between two strings
let name = 'Palash';
console.log(`Hello, ${name}!`);  // <-- No need to use + var + anymore
//=> Hello, Palash!

// Add two numbers
let num1 = 20;
let num2 = 10;
console.log(`Sum = ${num1 + num2} and Subtract = ${num1 - num2}`);
//=> Sum = 30 and Subtract = 10

6. For cycle

Common writing:

We can use the for loop to loop through an array like this:

let fruits = ['??', '??', '??', '??'];

// Loop through each fruit
for (let index = 0; index < fruits.length; index++) { 
  console.log( fruits[index] );  // <-- get the fruit at current index
}

//=> ??
//=> ??
//=> ??
//=> ??

Abbreviation:

We can use for The of statement achieves the same result with much less code, as shown below:

let fruits = ['??', '??', '??', '??'];

// Using for...of statement 
for (let fruit of fruits) {
  console.log( fruit );
}

//=> ??
//=> ??
//=> ??
//=> ??

7. Arrow function

Common writing:

To traverse the Array, we can also use the forEach() method in Array. But it needs to write a lot of code. Although it is less than the most common for loop, it is still better than for More of statements:

let fruits = ['??', '??', '??', '??'];

// Using forEach method
fruits.forEach(function(fruit){
  console.log( fruit );
});

//=> ??
//=> ??
//=> ??
//=> ??

Abbreviation:

However, using the arrow function expression allows us to write the complete loop code in one line, as follows:

let fruits = ['??', '??', '??', '??'];
fruits.forEach(fruit => console.log( fruit ));  // <-- Magic ?

//=> ??
//=> ??
//=> ??
//=> ??

Most of the time I use the forEach loop with arrow function. Here I put for The of statement and forEach loop are displayed to facilitate the use of code according to your preferences.

8. Find objects in the array

Common writing:

To find an object from the object array through one of the attributes, we usually use the for loop:

let inventory = [
  {name: 'Bananas', quantity: 5},
  {name: 'Apples', quantity: 10},
  {name: 'Grapes', quantity: 2}
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  for (let index = 0; index < arr.length; index++) {

    // Check the value of this object property `name` is same as 'Apples'
    if (arr[index].name === 'Apples') {  //=> ??

      // A match was found, return this object
      return arr[index];
    }
  }
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

Abbreviation:

WOW! We have written so much code to realize this logic. However, using the find() method in Array and the arrow function = >, we can do it in this line:

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
  return arr.find(obj => obj.name === 'Apples');  // <-- here
}

let result = getApples(inventory);
console.log( result )
//=> { name: "Apples", quantity: 10 }

9. Convert string to integer

Common writing:

The parseInt() function parses a string and returns an integer:

let num = parseInt("10")

console.log( num )         //=> 10
console.log( typeof num )  //=> "number"

Abbreviation:

We can achieve the same result by adding a + prefix to the string, as shown below:

let num = +"10";

console.log( num )           //=> 10
console.log( typeof num )    //=> "number"
console.log( +"10" === 10 )  //=> true

10. Short circuit evaluation

Common writing:

If we have to set a value other than false according to another value, we will generally use the if else statement, like this:

function getUserRole(role) {
  let userRole;

  // If role is not falsy value
  // set `userRole` as passed `role` value
  if (role) {
    userRole = role;
  } else {

    // else set the `userRole` as USER
    userRole = 'USER';
  }

  return userRole;
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

Abbreviation:

However, using short-circuit evaluation (|), we can do this with one line of code, as follows:

function getUserRole(role) {
  return role || 'USER';  // <-- here
}

console.log( getUserRole() )         //=> "USER"
console.log( getUserRole('ADMIN') )  //=> "ADMIN"

Basically, expression1 | expression2 is evaluated as a true expression. Therefore, this means that if the first part is true, you don't have to bother evaluating the rest of the expression.

Some additional points

Arrow function

If you don't need this context, the code can be shorter when using the arrow function:

let fruits = ['??', '??', '??', '??'];
fruits.forEach(console.log);

Find objects in array

You can use object deconstruction and arrow functions to streamline your code:

// Get the object with the name `Apples` inside the array
const getApples = array => array.find(({ name }) => name === "Apples");

let result = getApples(inventory);
console.log(result);
//=> { name: "Apples", quantity: 10 }

Short circuit evaluation alternatives

const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";

Coding habits

Finally, I want to talk about coding habits. Code specifications abound, but few people strictly abide by them. The reason is that they have their own set of code habits before the formulation of code specifications, so it is difficult to change their habits in a short time. Good coding habits can lay a good foundation for subsequent growth. Here are some benefits of developing specifications to let you understand the importance of code specifications:

  • Standardized code can promote teamwork.
  • Standardized code can reduce Bug handling.
  • Standardized code can reduce maintenance costs.
  • Standardized code is helpful for code review.
  • Developing the habit of code specification is conducive to the growth of programmers themselves.

What I'm looking at is Alibaba front end development specification. The code specification in it is very complete and basically universal. It's very useful after reading it. For space reasons, the following screenshots show the catalogue and some contents.

catalogue


1, Coding specification

2, Vue project specification

The above is the Alibaba front end development specification, which requires small partners click here You can download it for free.

Finally, I would like to end with a paragraph:

Code is our enemy because many of our programmers write a lot of shit code. If we can't get rid of it, we'd better try our best to keep the code simple.
If you like writing code - really, really like writing code - the less code you write, the deeper your love.

summary

This is the end of the article. At the end of the article, I put a small welfare. The following is a learning idea and direction on front-end development sorted out by Xiaobian in the learning process. To engage in Internet development, the most important thing is to learn technology well, and learning technology is a slow, long and arduous road. It can't be learned by passion for a moment, nor can it be learned by boiling for a few days and nights. We must develop the habit of studying hard at ordinary times, and need more accurate learning direction to achieve effective learning results.

Because there are many contents, only a general outline is put on, which requires more and detailed study of mind mapping Click my GitHub for free.
There is also a full set of free advanced web video tutorials, front-end architecture H5 vue node applet Video + data + code + interview questions!

We also discuss the problems of advanced web technology and solve the problems of advanced web technology.

Topics: Javascript Front-end html Interview