Question:
I’m quite new to JavaScript and I was wondering if it is possible to make anif
statement affect two separate parts of code. For example:if
statements like this: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.)
Answer:
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: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:if (test())
since you only call test
once, but I’ve kept it just so you can see it’s usable in many situations).If you have better answer, please add a comment about this, thank you!