Every language has its own quirks and JavaScript, the most used programming language, is no exception. This article will cover a plethora of JavaScript Shorthand Optimization tricks that can help you write better code, and also make sure this is NOT your reaction when you encounter them:
1. Multiple string checks
Often you might need to check if a string
is equal to one of the multiple values, and can become tiring extremely quickly. Luckily, JavaScript has a built-in method to help you with this.
// Long-hand
const isVowel = (letter) => {
if (
letter === "a" ||
letter === "e" ||
letter === "i" ||
letter === "o" ||
letter === "u"
) {
return true;
}
return false;
};
// Short-hand
const isVowel = (letter) =>
["a", "e", "i", "o", "u"].includes(letter);
2. For-of
and For-in
loops
For-of
and For-in
loops are a great way to iterate over an array
or object
without having to manually keep track of the index of the keys
of the object
.
For-of
const arr = [1, 2, 3, 4, 5];
// Long-hand
for (let i = 0; i < arr.length; i++) {
const element = arr[i];
// ...
}
// Short-hand
for (const element of arr) {
// ...
}
For-in
const obj = {
a: 1,
b: 2,
c: 3,
};
// Long-hand
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = obj[key];
// ...
}
// Short-hand
for (const key in obj) {
const value = obj[key];
// ...
}
3. Falsey checks
If you want to check if a variable is null
, undefined
, 0
, false
, NaN
, or an empty string
, you can use the Logical Not (!
) operator to check for all of them at once, without having to write multiple conditions. This makes it easy to check if a variable contains valid data.
// Long-hand
const isFalsey = (value) => {
if (
value === null ||
value === undefined ||
value === 0 ||
value === false ||
value === NaN ||
value === ""
) {
return true;
}
return false;
};
// Short-hand
const isFalsey = (value) => !value;
4. Ternary operator
As a JavaScript developer, you must have encountered the ternary operator
. It is a great way to write concise if-else
statements. However, you can also use it to write concise code and even chain them to check for multiple conditions.
// Long-hand
let info;
if (value < minValue) {
info = "Value is too small";
} else if (value > maxValue) {
info = "Value is too large";
} else {
info = "Value is in range";
}
// Short-hand
const info =
value < minValue
? "Value is too small"
: value > maxValue ? "Value is too large" : "Value is in range";
5. Function calls
With the help of the ternary operator
, you can also determine which function to call based on conditions.
IMPORTANT SIDE-NOTE: The call signature
of the functions must be the same, else you risk running into an errors
function f1() {
// ...
}
function f2() {
// ...
}
// Long-hand
if (condition) {
f1();
} else {
f2();
}
// Short-hand
(condition ? f1 : f2)();
6. Switch shorthand
Long switch cases can often be optimized by using an object with the keys as the switches and the values as the return values.
const dayNumber = new Date().getDay();
// Long-hand
let day;
switch (dayNumber) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
// Short-hand
const days = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
};
const day = days[dayNumber];
7. Fallback values
The ||
operator can set a fallback value for a variable.
// Long-hand
let name;
if (user?.name) {
name = user.name;
} else {
name = "Anonymous";
}
// Short-hand
const name = user?.name || "Anonymous";
That's all folks! š
Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja
Thanks for reading
Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork
Want to see what I am working on? Check out my Personal Website and GitHub
Want to connect? Reach out to me on LinkedIn
I am a Digital Nomad and occasionally travel. Follow me on Instagram to check out what I am up to.
Follow my blogs for bi-weekly new tidbits on Dev
FAQ
These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.
-
I am a beginner, how should I learn Front-End Web Dev?
Look into the following articles: Would you mentor me?
Sorry, I am already under a lot of workload and would not have the time to mentor anyone.
Latest comments (54)
For #2, instead of for-in, you can also use
For #4, I think nesting ternaries reduces readability and when you come back to it, or someone else tries to understand it, it introduces a lot of mental overhead.
Some great tips here! Thanks for sharing!
Thanks for this. Very helpful tips.
Note that I do think that code readability needs to be taken into consideration before using any available shortening option. Some of the examples above could add a perceived level of complexity and might have an unhelpful impressions on the dev.
Tip on ternary operation was bit on line "how to obfuscate code" line... Nested ternary operations make code harder to read, and resistant to change; if logic need to be changed, have to likely tear down first whole ternary operator mess to first of all understand logic, and secondly to be able to make logic change.
Number#4 should be avoided. Using ternary for something like that makes your code complex/hard to read. Please don't teach wrong practices as most of the newbies read these articles and start writing the bad code.
Number#5 should also be corrected as highlighted in other comments.
Haven't checked after #5 as I'm convinced after reaching the 5th point that this article lacks the actual and practical knowledge by the author and not worth reading.
I miss the unicorn š„²
thanks for sharing this stuff
This is Great
Most of your solutions have worse performance and sometimes different functionality. For example, a classic for-loop will execute even for the undefined items in sparse arrays; neither for-of nor array.prototype.forEach will do that.
Also, your function call shorthand requires that you are careful with semicolons, because otherwise, you might run into a
TypeError: undefined is not a function
when the previous statement also ended with brackets.const name = user?.name ?? "Anonymous";
Interesting and useful, thanks for sharing.
Iād suggest that any nested conditional statement can carry a heavy cognitive load. The author of this piece is demonstrating chained ternaries, where there is a single code path (no nested branching) that will return a value as soon as a condition is met or finally a default value if no conditions are met. A ternary expression is a different animal to if..else or switch statements, and it would be shame to see it thrown out in cases where it is the more suitable solution. There is an article by Eric Elliott on this subject.
Good article, thanks
Some great tips right here, thanks ššÆ
Some comments may only be visible to logged-in visitors. Sign in to view all comments.