Now making a comparison and executing a different piece of code, depending on the result is going to happen in probably every piece of code you are going to write and there are a few ways to achieve this
IF statements
These are probably the simplest to get to grips with
var a = 1; if (a == 1) { //is a is 1 then do whatever is here } //run this code whatever value a is
This code will check if a is equal to 1 and run the code inside the curly braces and then the rest of the code, if a is not 1 it will skip to after the curly brace and continue to run any other code.
What if you wanted it to do something for a==1 but something different for everything else
var a = 1; if (a == 1) { //is a is 1 then do whatever is here alert('a is 1'); } else { //run this code for any value of a that is NOT 1 alert('a is not 1'); } //run this code whatever value a is
Now this is better we can run different code for different values, but what happens is you have some code for a==1, some for a==2 and som for anything else?
var a = 1; if (a == 1) { alert('a is 1'); } else if (a == 2) { alert('a is not 1'); } else { alert('a is not 1 or 2'); } //run this code whatever value a is
This can be done for lots of different things but it is more concise to use switch when there are a number of expected results
Switch Statements
var a = 1; switch(a) { case 1: //code to run if a==1 break; //exits the switch statement case 2: //code to run is a==2 break; } //run this code whatever value a is
Now suppose you wanted to use a switch AND have some code run if a is not 1 or 2, JavaScript handles this case by having default in the switch which is the code it will execute if it doesn’t match any of the case statements
var a = 1; switch (a) { case 1: alert('a is 1'); break; case 2: alert('a is 2'); break; default: alert ('a is not 1 or 2'); }
Thats basically it for these statements they are very powerful and can be used in many situations including inside repeating sections of code called loops, but thats a topic for another day.