Tuesday, 15 November 2016

JavaScript While Loop & If Statement

In this lesson we will look at loops and if statements. Loops can execute a block of code as long as a specified condition is true. A while loop will loop through the block of code as long as the condition is true. The below is the syntax of a while loop:

while (condition) {
    code block to be executed
}

To stop your loop from running infinitely, you must update the condition after every execution of the code. An example of this would be to use a counter. See my example below.

As you can see the loop will run until the condition is no longer through. This is done by using a counter (i++).

The if statement is used to check if a condition is true and you want to run a block of code that might be related to that condition. Use the if statement to specify a block of JavaScript code to be executed if a condition is true. Use the else statement to specify a block of code to be executed if the condition is false. Syntax is below:

if (condition) {
    block of code to be executed if the condition is true} else { 
    block of code to be executed if the condition is false}

See the screenshots below for an example of this code being used.




Notice how when I change the value for 'hour', it runs a different block of code which places a different value into 'greeting' each time.

No comments:

Post a Comment