How to Refactor Nested If in JavaScript ?

Instead of creating nested if statements, you can simply return. Let’s take an example.

Assuming you have a code as shown :

function doStuff(a) {
  if (a > 10) {
    if (a > 400) {
      return 400;
    } else if (a > 100) {
      return 100;
    } else {
      return 1000;
    }
  } else {
    return 0;
  }
}

The first if statement can be converted into a one liner by simply using return,

function doStuff() {
  if (a < 10) return 0;
  if (a > 400) return 400;
  if (a > 100) return 100;
  return 100;
}