JavaScript abbreviation skills
- 2021-11-13 00:53:31
- OfStack
2. Merge arrays (at the beginning)
3. Cloning an array
4. Deconstructing assignment
5. Template literal
6. For cycle
7. The arrow function
8. Find objects in an array
9. Convert a string to an integer
10. Short circuit evaluation
Add a few points
The arrow function finds an alternative to short-circuit evaluation of an object in an array
1. Merge arrays
Common writing:
We usually use the concat () method in Array to merge two arrays. Merging two or more arrays with the concat () method does not change the existing array, but returns a new array. Look at a simple example:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇'].concat(apples);
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
Abbreviation method:
We can reduce the code by using the ES6 extension operator (...), as follows:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
The resulting output is the same as normal writing.
2. Merge arrays (at the beginning)
Common writing:
Suppose we want to add all the entries in the apples array to the beginning of the Fruits array instead of at the end as in the previous example. We can use
let apples = ['🍎', '🍏'];
let fruits = ['🥭', '🍌', '🍒'];
// Add all items from apples onto fruits at start
Array.prototype.unshift.apply(fruits, apples)
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
Now red apples and green apples will merge at the beginning instead of the end.
Abbreviation method:
We can still use the ES6 extension operator (...) to shorten this long code, as follows:
let apples = ['🍎', '🍏'];
let fruits = [...apples, '🥭', '🍌', '🍒']; // <-- here
console.log( fruits );
//=> ["🍎", "🍏", "🥭", "🍌", "🍒"]
3. Cloning an array
Common writing:
We can easily clone arrays using the slice () method in Array, as follows:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = fruits.slice();
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
Abbreviation method:
We can clone an array like this using the ES6 extension operator (...):
let fruits = ['🍉', '🍊', '🍇', '🍎'];
let cloneFruits = [...fruits]; // <-- here
console.log( cloneFruits );
//=> ["🍉", "🍊", "🍇", "🍎"]
4. Deconstructing assignment
Common writing:
When dealing with arrays, we sometimes need to "unpack" arrays into 1 heap of variables, as follows:
let apples = ['🍎', '🍏'];
let redApple = apples[0];
let greenApple = apples[1];
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
Abbreviation method:
We can achieve the same result with 1 line of code by deconstructing assignment:
let apples = ['🍎', '🍏'];
let [redApple, greenApple] = apples; // <-- here
console.log( redApple ); //=> 🍎
console.log( greenApple ); //=> 🍏
5. Template literal
Common writing:
Typically, 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 method:
With template literals, we can use inverted quotation marks (), so that we can wrap the expression in ${...} ` and embed it in a string, as follows:
// 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 the for loop to loop through an array like this:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
0
Abbreviation method:
We can use the for... of statement to achieve the same result with much less code, as follows:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
1
7. The arrow function
Common writing:
To traverse the array, we can also use the forEach () method in Array. But it takes a lot of code, less than the most common for loop, but still one point more than the for... of statement:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
2
Abbreviation method:
But 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 forEach loops with arrow functions. Here, I show for... of statements and forEach loops, which is convenient for everyone to use the code according to their own preferences.
8. Find objects in an array
Common writing:
To find an object from an array of objects through one of these properties, we usually use the for loop:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
4
Abbreviation method:
Wow! We have written so much code above to implement this logic. But using the find () method in Array and the arrow function = > Allow us to do it in one line like this:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
5
9. Convert a string to an integer
Common writing:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
6
Abbreviation method:
We can achieve the same result by adding a + prefix to the string, as follows:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
7
10. Short circuit evaluation
Common writing:
If we had to set a value other than an falsy value based on another value, 1 would normally 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 method:
But with short-circuit evaluation (), we can do this with one line of code, as follows:
let apples = ['🍎', '🍏'];
let fruits = ['🍉', '🍊', '🍇', ...apples]; // <-- here
console.log( fruits );
//=> ["🍉", "🍊", "🍇", "🍎", "🍏"]
9
Basically, expression1 expression2 is evaluated as a true expression. Therefore, this means that if Part 1 is true, you don't have to bother evaluating the rest of the expression.
Add a few points
Arrow function
If you don't need an this context, the code can be shorter when using the arrow function:
let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);
Find an object in an array
You can use object deconstruction and arrow functions to make the code simpler:
// 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 alternative
const getUserRole1 = (role = "USER") => role;
const getUserRole2 = role => role ?? "USER";
const getUserRole3 = role => role ? role : "USER";
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 concise.
If you like to write code--really, really like to write code--the less code you write, the more you love.