Conditional Statements (if/else statements)

The default behaviour of javascript is to interpret the code from the top to bottom. This isn't all that useful unless you can deterministically write everything

Conditional statements allow you to make decisions based on a yes/no question. (eg. if the answer to the question is yes, do one thing. If not, do something else).

The basic structure of of an if statement looks like this:

if( condition ) {
      // any statements inside the brackets,
      // executed if condition/test is true
}


- if indicates that it is a conditional statement
- the parenthesis enclose the true/false question called condition
- curly braces {} mark the beginning/end of the JavaScript code that should execute if the condition is true




var score = 10; 


if(score > 5){
  alert('You won!');
}

alert('Game Over');



Comparision operators:
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
== (equal to)
!= (not equal to)

=== (strict equal to. Compares value and type)
!== (strict not equal to)


'2' == 2     // true
'2' === 2    // false


You can use comparision operators to compare strings too:


    var enteredColor = prompt("what is your favorite color?");

    
    if(enteredColor == 'red'){
      document.body.style.backgroundColor = 'red';
    }


Take a look at this. It is doing something redundant...
var answer = prompt("How many moons does Saturn have?");

if(answer == 31){
    alert("Correct!");
}
if(answer != 31) {
    alert("Wrong");
}




An alternative path when the condition is false

if( condition ) {
      // statements 1
      // executed if condition is true
} else {
      // statements 2
      // executed if condition is false
}


Thus, we can modify the previous code to the following

// user answer the question 'How many moons does Saturn have?'. Store in variable answer

if(answer == 31){
  alert('Correct');
} else {
  alert('Wrong!');
}


Adding more expressive power - testing for multiple conditions:

if( condition1 ){
       // executed if condition 1 is true
   } else if( condition2 ){
       // executed if condition1 false, condition2 true
   } else {
       // executed if condition1, condition2 are both false
   }



You can repeat the else if statement as such:

 var x = 2;
   
   if( x < 0 ){
        alert("x < 0");    // x < 0 is true
   } else if( x < 1 ){
        alert("x < 1");    // x < 0 is false, x < 1 is true
   } else if( x < 2 ){
        alert("x < 2");    // x < 0 is false, x < 1 is false, x < 2 is true
   } else if( x < 3 ){
        alert("x < 3");    // x < 0 is false, x < 1 is false, x < 2 is false, x < 3 is true
   } else {
        alert("inside final else");  // x < 0 is false, x < 1 is false, x < 2 is false, x < 3 is false
   }
Notes

Complex Conditions -- Logical Operators

In the previous example, we were only testing against one variable (eg. x). What if we wanted to test against multiple variables?

Logical Operators:

|| (logical OR: one or the either must be true to be true)
basic syntax: A || B

(true || false) is true,
(true || true) is true,
(false || false) is false

(key == 'Y' || key == 'y') // evaluates to true if the variable key has either Y or y
ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse



&& (logical AND: both must be true to be true)
basic syntax: A && B

(true && false) is false,
(true && true) is true,
(false && false) is false
For example, (3 < 4 && 3 > 4) evaluates to (true && false) which evaluates to (false)

(key == 'Y' && key == 'y') // will never evaluate to true

(score > 90 && attendance > 90) // this could be true
ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse



! (logical NOT: negates boolean value)
basic syntax: !A

(!true) is false,
(!false) is true

A!A
truefalse
falsetrue



example: 04_logical_operators.html
var a = 9;
var b = 2;
var c = 3;

var valid = true;
var key = prompt("hit a key");

    
if(a < 10 && a > 1){
    alert("the value in a is between 1 and 10");
}



if( a >0 && b > 0 && c > 0){
   alert("a, b, c are greater than 0");
}


if( key == 'n' || key == 'N') {
  // user hit n or N. 
}

if ( !valid ) {
  // if not valid (what does the variable valid have to be in order
  // for this block to be executed
}
Notes

Tips

- type in both the curly braces before you type the code inside
- indent code within braces
- use == for comparison. = is for assignment
Notes

While loops

There are times you want the computer to repeat the same series of steps over and over. For example, may want to change the color of 10000 elements in an array.

while loops repeat the code inside the brackets as long as the condition is true. Every time it finishes with the code inside the bracket, it tests the condition inside the parenthesis.

while (condition){
  // statements;
}



var x = 0;
while( x < 10 ){
  document.write(x + "<br>");
  x = x + 1;
}

is equivalent to

document.write(0 + "<br>");
document.write(1 + "<br>");
document.write(2 + "<br>");
document.write(3 + "<br>");
document.write(4 + "<br>");
document.write(5 + "<br>");
document.write(6 + "<br>");
document.write(7 + "<br>");
document.write(8 + "<br>");
document.write(9 + "<br>");


When using while loops, it is important that you make sure that the condition you are testing for eventually turns to false or else you will have created an infinite loop.

var num = 1;
while (num <= 4 ){
  document.write(num + "<br>");  // this is an infinite loop
}


Loops are often used in conjunction with arrays. [04_whileloop.html]

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

var counter = 0;

while (counter < days.length){
  document.write(days[counter] + ', ');
  counter++;
}
Notes

For loops

For loops are often used to repeat a block of code a number of times


  for(init; test; update){
       statement;
   }
  1. set init condition,
  2. if test is true,
  3. execute statements,
  4. update condition.
  5. Go back to test until false





for(var i=0; i<100; i++){ document.write(i + "<br>"); }
Starting with the initial condition i=0, as long as i < 100, execute statements then increment i by 1. (In plain English, iterate over the statement 100 times)



<script>
  var pgraphs = document.getElementsByTagName("p"); // get all elements with tag <p>
  pgraphs[0].style.color = "red";
  pgraphs[1].style.color = "red";
  pgraphs[2].style.color = "red";
  pgraphs[3].style.color = "red";
  pgraphs[4].style.color = "red";
</script>


can be turned into a for loop:
<script>

  var pgraphs = document.getElementsByTagName("p"); // get all elements with tag <p>
  
  for(var i = 0; i < pgraphs.length; i++){
    pgraphs[i].style.color = "red";
  }

</script>


Note that document.getElement... functions returns an element object (in HTML DOM) which represents an HTML element.
HTML DOM Element Object@W3Schools


Examples:
- [no loop: 04_selectbyclass_noloop.html], [using loop: 04_selectbyclass_loop.html]
- [search using for loops and if statements: 04_search.html]
Notes