current position:Home>10 great JavaScript shorthand skills

10 great JavaScript shorthand skills

2021-08-23 12:59:27 Lee, don't stay up late

What I want to share today is 10 It's a great JavaScript Shorthand method , Can speed up development , Let your development work get twice the result with half the effort .

Let's get started !

1. Merge array

Common writing :

We usually use Array Medium concat() Method to merge two arrays . use concat() Method to merge two or more arrays , The existing array... Will not be changed , Instead, it returns a new array . Look at a simple example :

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

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

Shorthand method :

We can do that by using ES6 Extension operator (...) To reduce code , As shown below :

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

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

The output is the same as the normal writing method .

2. Merge array ( At the beginning )

Common writing :

Suppose we want to apples All items in the array are added to Fruits The beginning of the array , Instead of putting it at the end as in the previous example . We can use Array.prototype.unshift() To do that :

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 .

Shorthand method :

We can still use ES6 Extension operator (...) Shorten this long code , As shown below :

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

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

3. Clone array

Common writing :

We can use Array Medium slice() Method to easily clone an array , As shown below :

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

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

Shorthand method :

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

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

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

4. Deconstruct assignment

Common writing :

When working with arrays , We sometimes need to put arrays “ Unpack ” Into a pile of variables , As shown below :

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

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

Shorthand method :

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

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

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

5. Template literal

Common writing :

Usually , When we have to add an expression to a string , We'll do that :

// 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

Shorthand method :

Through template literal , We can use backquotes (), So we can wrap the expression in ${...}\` in , Then embedded 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 loop

Common writing :

We can use for Loop loops 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
}

//=> 
//=> 
//=> 
//=> 

Shorthand method :

We can use for...of Statement to achieve the same result , And 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 :

You're going through groups , We can also use Array Medium forEach() Method . But you need to write a lot of code , Although more than the most common for Fewer cycles , But still more than for...of More sentences :

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

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

//=> 
//=> 
//=> 
//=> 

Shorthand method :

But using the arrow function expression , Allows us to write complete loop code in one line , As shown below :

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

//=> 
//=> 
//=> 
//=> 

Most of the time I use functions with arrows forEach loop , Here I put for...of Statement and forEach Cycles are shown , It is convenient for everyone to use the code according to their preferences .

8. Find objects in an array

Common writing :

To find an object from an object array through one of its properties , We usually use 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 }

Shorthand method :

wow ! We have written so much code to implement this logic . But use Array Medium find() Methods and arrow functions =>, Allow us to do things like this :

// 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 :

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

let num = parseInt("10")

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

Shorthand method :

We can add... Before the string + Prefix to achieve the same result , 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 according to another value, it is not falsy value , You usually use if-else sentence , Just 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"

Shorthand method :

But using short-circuit evaluation (||), We can do this in one line of code , As shown below :

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

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

Basically ,expression1 || expression2 Assessed as really expression . therefore , This means that if the first part is true , You don't have to worry about evaluating the rest of the expression .

Add a few

Arrow function

If you don't need to this Context , The code can also be shorter when using the arrow function :

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

Find objects in an 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 . The reason is , Most of them are before the code specification , Has its own set of code habits , It's hard to change your habits in a short time . Good coding habits can lay a good foundation for subsequent growth . below , List a few benefits of developing a specification , Let us understand the importance of code specification :

  • Standardized code can promote teamwork .
  • Standardized code can reduce Bug Handle .
  • Standardized code can reduce maintenance costs .
  • Standardized code helps code review .
  • Get into the habit of code normalization , It's good for the growth of programmers themselves .

What I'm looking at myself is 《 Alibaba front end development specification 》, The code specification inside is very complete , And basically universal , It's very useful after reading . The space for , The following is a screenshot showing the directory and some contents , complete PDF Click here You can download for free .

Catalog


One 、 Coding standards

Two 、Vue Project specifications

That is 《 Alibaba front end development specification 》, A little friend in need Click here You can download for free .

Last , I'd like to end with a passage :

Code is our enemy , Because many of our programmers write a lot of shit code . If we can't get rid of , Then it's best to do your best to keep the code simple .
If you like to write code —— Really? , I really like writing code —— The less code you write , The deeper your love .

copyright notice
author[Lee, don't stay up late],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210823125924094p.html

Random recommended