• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Is it possible to make an “if” statement affect two separate parts of code?

Resolved: Is it possible to make an “if” statement affect two separate parts of code?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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:
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:
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.)

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:
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:
(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).

If you have better answer, please add a comment about this, thank you!

javascript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: PyCharm cannot see my newly compiled .pyc see on import

27/03/2023

Resolved: I am facing ERR_HTTP2_PROTOCOL_ERROR on my website

27/03/2023

Resolved: TypeScript does not recognize properties when instantiating interface array

27/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.