7 JavaScript Powerful Optimization Tricks You Need To Know
<p>Every language has uniqueness, and JavaScript, the most widely used programming language, is no different.</p>
<p>This blog post will discuss some JavaScript Generic Optimization tricks that will help you write better code and make sure that the following is just not your response when you come all over them:</p>
<h1>1. Fallback Values</h1>
<p>The fallback place to display some adjusting.</p>
<p>If the value is [] or 0, using logical OR || does not give you the expected results.</p>
<p>The bullish symbiosis would be a better solution?? If the defined value is null or undefined, only use the fallback values.</p>
<pre>
// Lengthy
let name;
if (user?.name) {
name = user.name;
} else {
name = "Anonymous";
}
// Shortly
const name = user?.name ?? "Anonymous";</pre>
<h1>2. Shortly For Switching</h1>
<p>Long switch cases are commonly maximized by using an object with the keys acting as switches and the values trying to act as return values.</p>
<pre>
const dayNumber = new Date().getDay();
// Lengthy
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";
}
// Shortly
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
// Or
const days = `Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday`.split(
","
);
const day = days[dateNumber];</pre>
<h1>3. Calls To Functions</h1>
<p>You can also use the binary operator to decide which function to call based on conditions.</p>
<blockquote>
<p>The call patterns of the functions must be the same or you will end up facing errors.</p>
</blockquote>
<pre>
// Lengthy
function f1() {
// ...
}
function f2() {
// ...
}
// Shorter
condition ? f1() : f2();</pre>
<h1>4. Multiple String Checks</h1>
<p>It is popular to need to check if a string is equal to one of the multiple values, which can quickly become irritating.</p>
<blockquote> </blockquote>
<p><a href="https://javascript.plainenglish.io/7-javascript-powerful-optimization-tricks-you-need-to-know-f0b5da2933de">Read More</a> </p>