Home > Back-end >  Use only the variable that caused an if statement to trigger, within the if statement
Use only the variable that caused an if statement to trigger, within the if statement

Time:05-24

say you have an if statement:

try {
    if (!a || !b || !c || !d) {
      let nullVariable = ???;
      // use the variable that is null
      throw nullVariable
    }
} catch (ex) {
  log.debug(`${ex} is not defined`);
}

Is there a built in way to see which variable was set to null, without creating an if statement for each individual variable?

CodePudding user response:

You can put the assignment inside the if condition expression.

let a, b, c, d;
a = 3;
b = "foo";
d = {x: 10};
let nullVariable = (!a && 'a') || (!b && 'b') || (!c && 'c') || (!d && 'd');
if (nullVariable) {
    console.log(`${nullVariable} is not defined`);
}

CodePudding user response:

You can extract the variable name using object shorthand.

const fn = ({ a, b, c, d }) => {
  let nullVariable = Object.entries({ a, b, c, d }).find(([_, val]) => !val)?.[0];
  
  if(nullVariable)
    console.log(nullVariable   ' is falsy');
};

fn({ a: 1, c: 2, d: 3 });
fn({ a: 1, b: 2, c: 3 });
fn({ a: 1, b: 2, c: 3, d: 4 });

  • Related