Is it possible to make an "if" statement affect two separate parts of code?

I’m quite new to JavaScript and I was wondering if it is possible to make an if statement affect two separate parts of code. For example:

console.log(1);
console.log(2);
console.log(3);

The code above should print the numbers 1, 2, and then 3 in that order, but I want to add a test to it. If the test passes, all three commands should run, but if it fails only a 2 should be printed. I could add two if statements like this:

if (test()) {console.log(1)}
console.log(2);
if (test()) {console.log(3)}

My problem with this is the test() function is being run twice. Is there a way to only run the test once while preserving the order of the numbers? Sorry if there’s an obvious answer and I’m just missing it.

(I should add that this is just an example of 3 events that have to happen in order, so I need an answer that would work not just for printing consecutive numbers but anything situation where you would want 3 things to happen in order.)

>Solution :

This is best done by storing the value in a variable that will handle the control flow execution (this variable is known as a flag). You can make it as simple as this:

let testResult = test();
if (testResult) {
    console.log(1);
}
console.log(2);
if (testResult) {
    console.log(3);
}

This will ensure that if testResult is false (i.e. test returns false or a falsy value) then you will only have 2 printed, but if test returns true or a truthy value, then 1, 2, 3 will all be printed.

If you only want a single if statement, then use if-else and print 2 in both of them:

let testResult = test();
if (testResult) {
    console.log(1);
    console.log(2);
    console.log(3);
} else {
    console.log(2);
}

(note you could eliminate the first line in the code block above and just use if (test()) since you only call test once, but I’ve kept it just so you can see it’s usable in many situations).

Leave a Reply