paint-brush
Why Should Every Javascript Developer Avoid Using if Statements by@jacobsood
10,772 reads
10,772 reads

Why Should Every Javascript Developer Avoid Using if Statements

by Jacob SoodJune 24th, 2022
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Using `if` statements is a clunky way of writing code and should be avoided wherever possible. Overusing them in areas where they can be avoided will make your life harder when it comes the time to revisit the code in a few months' time. This disrupts the “flow” and contributes to lower overall efficiency.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Why Should Every Javascript Developer Avoid Using if Statements
Jacob Sood HackerNoon profile picture


Stop using if statements unless absolutely necessary.

Using if statement is a clunky way of writing code and should be avoided wherever possible (in most situations, this is almost 100% of the time).


Don’t get me wrong, if statements are useful in certain scenarios and are there for a reason. However, overusing them in areas where they can be avoided will not only make your life harder when it comes the time to revisit the code in a few months' time, but also impact the time it takes for a dev to understand the context of the code and continue with the task that has been assigned to them. This disrupts the “flow” and contributes to lower overall efficiency. Less is more.


Looking at the code snippet below, we’re retrieving a card from the database by encrypted card number and returning a validation response based on certain conditions.


async validateCard(encryptedCardNumber) {
  const card = await this.lookupCard(encryptedCardNumber);
  if (!card) {
    console.log(NotFoundResponse.message);
    return NotFoundResponse;
  }
  else if (card.isBlacklisted) {
    console.log(BlacklistedReponse.message);
    return BlacklistedResponse;
  }
  else if (card.isDeleted) {
    console.log(DeletedResponse.message);
    return DeletedResponse;
  } 
  else if (card.status !== CardStatus.active) {
    console.log(InactiveResponse.message);
    return InactiveResponse;
  }
  else {
    console.log(ValidResponse.message);
    return ValidResponse;
  }
}


Having these many if statements not only require quite a bit of effort to decipher, but as more conditions get added, we’ll soon be scrolling up and down to ensure each and every case has been met, adding more fuel to the fire. Alongside this, there also seems to be code duplication which can be extracted for the sake of maintainability.


The example below does just that. It replaces the countless if statements with and (short-circuit evaluation), which is a whole lot neater and easier to understand. For those that aren’t familiar with disjunction and conjunction, I’d highly recommend looking it up, but here’s a brief description:
  • Logical AND (&&) evaluates operands from left to right, returning immediately with the value of the first operand it encounters; if all values are , the value of the last operand is returned.
  • The logical OR (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. With short-circuit evaluation, it simply returns the first truthy expression.


async validateCard(encryptedCardNumber) {
  const card = await this.lookupCard(encryptedCardNumber);
  
  const response = 
    !card && NotFoundResponse ||
    card.isDeleted && DeletedResponse || 
    card.isBlacklisted && BlacklistedResponse ||
    card.status !== cardStatus.active && InvalidStatus ||
    ValidResponse;

  console.log(response.message);
  return response;
}


As business requirements change, so does the code. In some cases that may be removing the code entirely, but in others, it’s expanding onto what’s already there. Here’s a popular interview question that gets asked, and is concerned with your ability to create a somewhat scalable solution


Create a function that converts a given number between 1–10 into words


Simple right? Just having a bunch of if (or switch) statements in the function should do, and impress the interviewer.


function convertIntegerToText(num) {
  if (num === 1) return "one";
  if (num === 2) return "two";
  if (num === 3) return "three";
  // ...
  if (num === 10) return "ten";
}


But what if they then say this,


The requirements have changed. We now want to use this function to convert numbers between 1–100 into words


What are you going to do now? Just keep writing if statements for each and every scenario? What if they later change the requirements to convert numbers up to 1000?


The better approach is to think of a scalable solution from the get-go. A key fundamental principle to keep in mind when designing, architecting, writing, and maintaining code is how time affects the sustainability of software and how to make your code resilient over time.


A scalable solution is therefore a code where there is either no if statements whatsoever or a few statements that can cover the majority of the cases, if not all, with minimal to no modifications required.


const ONES = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
const TEENS = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
const TENS = ["", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"];

function convertIntegerToText(num) {
  if (num < 20) 
    return ONES[num] ?? TEENS[num - 10];
  
  if (num < 100)
    return `${TENS[Math.floor(num / 10)]} ${convertIntegerToText(num % 10)}`;
  
  if (num < 1000)
    return `${ONES[Math.floor(num / 100)]} hundred ${convertIntegerToText(num % 100)}`;
  
  throw new Error("Number too high");
}


To end things off, have a look at the snippet below, and judge for yourself which one you think is highly scalable, maintainable, easier to read, and will help you stay in the state of flow if you do come across it?


// home.jsx
function getCompanyTemplate(company) {
  if (company === "apple") {
    return <AppleTemplate />
  }
  if (company === "samsung") {
    return <SamsungTemplate />
  }
  if (company === "sony") {
    return <Sony />
  }
  if (company === "lg") {
    return <Lg />
  }
}
  
// OR
  
// index.jsx
export const templates = {
  apple: <Apple />,
  samsung: <Samsung />,
  sony: <Sony />,
  lg: <Lg />,
}

// home.jsx
import { templates } from "./index"
function getCompanyTemplate(company) {
  return templates[company];
}


My previous showcases an in-depth scalable frontend solution without any if statements. Be sure to check it out!



Also published .
바카라사이트 바카라사이트 온라인바카라