13 JavaScript Shorthands That Will Make You Look Like a Pro
Must-read for young JavaScript programmers
Programmers’ time is expensive.
That’s why their productivity matters.
There exist some shorthands to save developers time and can make code look cleaner.
Of many shorthands, some also make the code less readable. As a result, the overall complexity of the code increases.
Therefore, you should use abbreviations only when you are sure that they will not cause problems in the future.
Here I am mentioning thirteen javascript shorthands that will save your time.
1. Declaring Variable
In javascript, variables are declared with the let
keyword.
When you don’t assign an initial value to any variable with a let
statement, the variable is declared but its value is undefined
.
let a = 30;
let b = 100;
let c;
console.log(a, b, c)
// result : 30 100 undefined
You could have declared all three variables above using a single let
statement like this:
let a= 30 , b= 100, c;
console.log(a, b, c);
// result : 30 100 undefined
You can also use an array to declare the variable in a single line.
let [a,b,c] = [30, 100]
console.log("value of a", a)
console.log("value of b", b)
console.log("value of c", c)
//result:value of a 30
value of b 100
value of c undefined
2. Using the ternary operator
Typically, in an if..else statement, the if statement is executed when the expression is true, and the else statement is executed when the expression is false.
Here is an example:
if(num === 2){
console.log("Hello");
}
else{
console.log("Number not 2");
}
In the above code, if the expression num === 2
is true, the message “Hello” will be printed, and if the expression is false, the else statement will be executed.
The ternary statement can help you replace an if…else statement. The syntax of a ternary operator is as follows:
[condition]? [true output] : [false output]
An example:
const result = x%2 == 0 ? "x is even": "x is not even"
The first operand x%2 == 0
evaluates to a boolean. If the value of the first operand is truthy, then the second operand is evaluated and its value is returned.
If the value of the first operand is falsy, then the value of the third operand is evaluated and its value is returned.
The above if…else statement can be shortened by using a ternary operator.
num === 2 ?console.log("Hello"): console.log("Number not 2");
One more example to make things clear
//longhand
const rank = 59
if (rank <= 10){
return "Good rank"
}else{
return "Bad rank"
}
//shorthand
const rank1 = 59
return rank1<= 10 ? "Good rank": "Bad rank"
3. Short circuit evaluation
In javascript, one variable value can be assigned to a different variable.
Sometimes, when you assign a variable value to another variable, you want to ensure that the variable’s value being assigned is not null, undefined, or empty.
When you read other people’s javascript code, they mostly use an if
statement to check this.
They write code like this:
if(var1 !== null || var1 !== undefined || var1 !== ""){
let var2 = var1
}
In javascript, the above code can be written as:
let var2 = var1 || "hello"
In the code, the value contained in var1 will be assigned to the variable var2 only if var1 has a non-falsy value.
Falsy values include undefined
, “”
(empty string), null
, 0
, and false
.
If var1 contains any falsy values, then var2 will be assigned the value “hello”.
Here is an example:
let var1 = "hey"
let var2 = var1 || "hello"
console.log(var2)
//result: hey
let var1;
let var2 = var1 || "hello"
console.log(var1)
console.log(var2)
//result :
undefined
hello
If you want to use more than one statement, you can:
let var2;
let var1;
let var3 = var2 || var1 || "hello"
console.log(var3)
//result: hello
If you use the || operator to select the first non-falsy value then 0
, “”
(empty string) and false
are ignored.
Under certain circumstances, it is necessary to assign values such as 0
, “”
(empty string), and false
.
Replacing the || operator with the ?? operator
An example:
let var1 = 0;
let var2 = var1 || "hello";
console.log(var2);
//result: hello
In the above code, since the value of var1 equals zero and is a falsy value, that’s why var2 is assigned to hello.
Now let’s replace the operator || with ??.
let var1 = 0;
let var2 = var1 ?? "hello";
console.log(var2)
//result: 0
In the code above, since the value of var1 is equal to 0 and the ?? operator works with 0, that’s why var2 is assigned to 0.
When you use the ?? operator remember this one thing:
?? operator does not have a higher or lower precedence like && and || operators. If you use the operator with && and || operator you need to use parentheses to be more specific.
Here are some examples:
(x ?? y) || z
-> ?? first, then ||
x ?? y || z
-> It will give a syntax error: parentheses are required
The name of ?? the operator is “nullish coalescing”.
4. Swapping two variables
Most programmers use a third variable to swap two variables.
let a = 8, b = 48;
const temp = a;
a = b;
b = temp;
It is possible to swap two variables without using a third variable like this:
let a = 8 , b = 48;
[a,b] = [b,a]
5. Arrow function makes things easy
To declare any function we use the function keyword followed by these things:
An identifier that acts as the name of the function.
A pair of parentheses with a comma-separated list of zero or more identifiers.
The function also has a pair of curly braces with one or more statements inside it.
Example 1:
function dis(a1, b1, a2, b2){
let a = b1-a1;
let b = b2-a2;
return Math.sqrt(a*a + b*b);
}
The above function can be represented using an arrow function.
Arrow function
In an arrow function, you don’t need to use the function
keyword.
The arrow function is an expression, not a statement, so a function name is not needed either.
If you take a look at the general form of the arrow function, it consists of a list of parameters separated by one or more commas. An arrow is present in the general form.
Here is an example to write a function using the arrow function:
function multiply(a, b){
return a * b;
}
//Arrow function
const multiply = (a, b) => a * b;
To write example 1 with the help of the arrow function we will do this:
const dis = (a11, b11, a22, b22) => {
let a = b11-a11;
let b = b22-a22;
return Math.sqrt(a*a + b*b);
}
6. String on Steroids
In our day-to-day work, we use the +
operator to concatenate any number of string values with variables.
With the help of the ES6 template literal, you can do it in a much simpler way.
//Longhand
console.log('Hello I obtained a rank' + rank + 'in this' + year);
//Shorthand
console.log(`Hello I obtained a rank $(rank) in this ${year}`);
7. Exponent shorthand
Math.pow() given two arguments, base, and exponent, returns the base to the power of the exponent.
console.log(Math.pow(7 , 2));
console.log(Math.pow(4, 0.5));
//result:
49
4
There is an alternative to Math.pow(). You can use it as a shorthand for this mathematical function.
console.log(7**2)
console.log(4**0.5)
//result:
49
2
The ** operator allows you to calculate the exponent without using any mathematical functions.
8. Spread Operator
Programmers generally use for loops to find the minimum and maximum numbers in an array.
But the spread operator makes it much easier to find the maximum and minimum number. You can do it in one line.
const abc = [4,8,12,27,2,7]
console.log(Math.max(...abc));
console.log(Math.min(...abc));
//result:
27
2
Concatenation of two arrays
With the help of a spread operator, two arrays can be easily concatenated.
You don’t have to use concat
for doing this.
Here is an example:
const abc = [2,3,4]
const xyz = [7,8,9]
//longhand
let mnp = abc.concat(xyz);
//shorthand
mnp = [...abc, ...xyz];
Insert new elements into an array
You can use the spread element to push a new element in an array.
You can stop using the push
function to do this.
Here is an example:
let abc = [2,3,4];
//Longhand
abc.push(5);
abc.push(6);
//shorthand
abc = [...abc, 5,6];
9. Convert any value to boolean
With the help of double exclamation marks (!!), you can convert any value to a boolean value.
console.log(!![])
console.log(!!3)
console.log(!!678)
console.log(!!0)
console.log(!!"")
//result:
true
true
true
false
false
10. The for loop can be shortened
To loop through an array, we’ve been using a traditional for loop for a long time.
To do the same, we have many other options. We can use for…of to iterate through an array. We can also use the forEach() method to iterate through arrays.
To access a particular index, we can use for…in.
Here are some examples.
const numberList = [5,3,9,4,6]
//Longhand
for(let i =0; i < numberList.length; i++){
console.log(numberList[i]);
}
//Shorthand using for...of
for(const value of numberList){
console.log(value);
}
//Shorthand using forEach()
numberList.forEach(value => console.log(value));
//Shorthand using for...in
for(const i in numberList){
console.log(`Position: ${i} and Value: ${numberList[i]}`);
}
11. Round numbers without Math.floor
You can round numbers without using the Math.floor() function.
To do this we use the ~~
operator.
Here is an example:
//Longhand
Math.floor(8.75)
//Shorthand
~~7.89
//results:
8
7
12. Object Property Assignment
If the variable name in your code and object key names are the same, then you can choose not to write the object literals.
It is not necessary to mention both the key and the value.
let bookName = 'xyz'
let bookAuthor = 'abc'
//Longhand
let Details = {bookName : bookName, bookAuthor : bookAuthor};
//shorthand
let Details = {bookName, bookAuthor};
13. Decimal Base Exponents
1e5 means 1 followed by 5 zeros (100000).
Similarly, 1e4 means 1 followed by 4 zeros (10000).
You can use this while writing code in JavaScript.
//Longhand
for(let i = 0; i < 100000; i++) {
//do whatever you like
}
//Shorthand
for(let i = 0; i < 1e5; i++){
//do whatever you want
}
//Here is a list for your convenience
1e0 = 1
1e1 = 10
1e2 = 100
1e3 = 1000
1e4 = 10000
1e5 = 100000
1e6 = 1000000
1e7 = 10000000