Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use only the variable that caused an if statement to trigger, within the if statement

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading