JS shorthands
Shorthands (no matter what language we are working in) always help to make your code shorter, optimized and much cleaner. Here I want to recap some helpful shorthand coding techniques in Javascript that will surely help you a lot.
- Ternary operator
We can use “conditional ternary operator” instead of if … else statement and use only one line of code:
// Longhand
let name = document.querySelector(‘input.name’).value,
user;
if(name){
user = name;
} else {
name = "Anonymous"
}
// Shorthand
const user = name ? name : "Anonymous"
2. Null, Undefined or Empty
You can check if a variable is null, undefined or empty with a simple shorthand:
// Longhand
if(myVariable !== undefined || myVariable !== "" || myVariable !== null){
...
}// Shorthand
if(myVariable){
...
}
3. Convert string into a number
A very useful shorthand if you use some parseInt or parseFloat:
// Longhand
const quantity = parseInt("250")
const price = parseFloat("432.50")// Shorthand
const quantity = +"250" // converts to int
const price = +"432.50" // converts to float
4. Default parameter values
Assign default values to variables:
// Longhand
function yourPet(name, age, type){
if(type === undefined){
type = ‘dog;
}
return `Your ${type} called ${name} has ${age} years old`
}// Shorthand
yourPet = (name, age, type = ‘dog’) => (`Your ${type} called ${name} has ${age} years old`)
5. Destructuring assignment
Is a very useful way to shorten your code with objects:
const clientsAge = {
peter : 18,
claire: 25,
john: 35,
mathew: 40
} // Longhand
let peter = clientsAge.peter,
claire = clientsAge.claire,
john = clientsAge.john,
matthew = clientsAge.mathew;// Shorthand
const { peter, claire, john, matthew } = clientsAge;
6. Declaring variables
A very similar shorthand like “destructuring objects” but now for multiple variables:
// Longhand
let a = ‘hello’,
b = 5,
c;// Shorthand
let a = ‘hello’, b = 5, c;
7. For loop
Other ways to use a loop, but with less code:
const clients = [“peter”, “claire”, “john”, “matthew”]// Longhand
for ( let index = 0; index < clients.length; index ++ ) {
console.log(clients[index]);
}// Shorthand
for ( let client of clients ) {
console.log(client);
}for ( let index in clients ) {
console.log(clients[index]);
}
8. Shor-circuit logical operator
// Longhand
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}// Shorthand
const variable2 = variable1 || 'new';
Another example for this is logical shorthand:
let variable1;
let variable2 = variable1 || 'bar';
console.log(variable2 === 'bar'); // true
variable1 = 'foo';
variable2 = variable1 || 'bar';
console.log(variable2); // foo
9. Spread operator
I like a lot this way to join and clone an array. After, I made concat() to join 2 arrays, and slice() to clone one. But now. Less code!
const clients = [ “peter”, “claire”, “john”, “matthew” ]// Longhand
// Join arrays
const newClients = [“lola”, “marcos”, “daniel”, “pedro”].concat(clients);// Clone arrays
const newClients = clients.slice();// Shorthand
// Join arrays
const newClients = [“lola”, “marcos”, “daniel”, “pedro”, ...clients]// Clone arrays
const newClients = [...clients]
10. Assignment operators
This operators are very useful for arithmetics operations:
// Longhand
a = a + 1;
b = b - 1;
c = c * 50;// Shorthand
a = a++;
b = b -;
c* = 50;
But we have more! Look this examples thinking that a = 20 and b = 10
a += b // Result a = 30
a -= b // Result a = 10
a *= b // Result a = 200
a /= b // Result a = 2
a %= b // Result a = 0
11. Decimal base exponents
This shorthand is a way to write numbers without zeros. For example, 1e5 means that 1 is followed by 5 zeros (100.000)
// Longhand
for (let index = 0; index < 10000000; index++)// Shorthand
for (let index = 0; index < 1e7; index++)
12. Object.entries()
Honestly, I learned this shorthand a few days ago and I think it’s very important to add it in this article. This is a shorthand introduced in ES8 and allows you to convert a literal object into a key/value pair array:
const clients = { client1: ‘Theo’, client2: ‘Vincent’, client3: ‘PK’, client4: ‘Edrei’ };
const arrayClients = Object.entries(clients);// Result:
[
[ ‘client1’, ‘Theo’ ],
[ ‘client2’, ‘Vincent’ ],
[ ‘client3’, ‘PK’ ],
[ ‘client4’, ‘Edrei’ ],
]
13. Object.values()
This shorthand is very similar to Object.entries() but without the key. Is was introduced in ES8 too.
const clients = { client1: ‘Theo’, client2: ‘Vincent’, client3: ‘PK’, client4: ‘Edrei’ };
const arrayClients = Object.entries(clients);// Result:
[ ‘Theo’, ‘Vincent’, ‘PK’, ‘Edrei’ ]
14. && (and) short circuit
You can get a fancy code with this shorthand. If you are calling a function only if a variable is true, you can use:
// Longhand
if (isClient) {
sendNewsletter();
}// Shorthand
isClient && sendNewsletter();
15. ~~ (double not bitwise operator)
This shorthand is a substitute for Math.floor() method:
// Longhand
const size = Math.floor(10.25); // Result 10// Shorthand
const size = ~~10.25; // 10
16. Find max/min number in array
We can use a loop to find the max and min value in an array, but you can also use Math.max() and Math.min() and remove a few lines of code:
const arrayNumbers = [ 1, 50, 28, 32 ];// Longhand (one way to resolve that)
function findMaxMin(array, maxmin) {
if (maxmin === "maximum") {
var max = array[0];
for (var i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
else if (maxmin === "minimum") {
var min = array[0];
for (var j = 1; j < array.length; j++) {
if (array[j] < array[j-1]) {
min = array[j];
}
}
return min;
}
}
console.log(findMaxMin(arrayNumbers, "maximum")); // 50
console.log(findMaxMin(arrayNumbers, "minimum")); // 1// Shorthand
Math.max.apply( Math, arrayNumbers ); // 50
Math.min.apply( Math, arrayNumbers ); // 1
But, like we have seen, we can add a spread operator and create a new shorthand:
// Shorthand
Math.max(...arrayNumbers); // 50
Math.min(...arrayNumbers); // 1
I hope you have learned some shorthands!