Home > Blockchain >  Does IF statement executes whenever condition is met or it is just once?
Does IF statement executes whenever condition is met or it is just once?

Time:05-27

how does the "if" statement works in javascript? Does it check for conditions only once? or it executes whenever the condition is met doesn't matter if initially, the condition was false but later it became true.

For example, if the condition is based on a number variable. like, execute if the number is 1.

When I npm start, the Number variable is 0 so the condition is false initial so If statement won't execute the code block, after some processing is done, the Number is changed to 1, so the condition is now favourable, does that mean "if" statement will now execute the code block? or is it only once that is condition was false at starting, now it won't execute even if condition is now true.

CodePudding user response:

JavaScript runs linearly, with the exception of asynchronous code. Asynchronous code is something like a promise .then chain or async/await or callback functions. These are the only pieces of code that will run at a later time and not immediately upon interpretation. An if statement will run if the condition being checked is truthy, AT THE TIME OF EXECUTION. So to answer your question, no, it will not run as soon as the condition becomes true. It must be true when the if statement is checked and not at a later time.

CodePudding user response:

An if statement alone will only execute one time. You could set up some type of loop to recheck the condition after you alter the number to see if it will now pass into the true side of the statement.

CodePudding user response:

If statement works only once if it is not in loop. if you want to test something again and again you can use setTimeout() function with it so it will repeat itself. JS is linear language.

  • Related