Control flow
Control flow allows you to direct the flow of code depending on the conditions which are given. Here are the main operators used in comparison evaluations.
Comparison operators
- <
- Less than.
- >
- Greater than.
- >=
- Greater than or equal to.
- <=
- Less than or equal to.
4 > 10 // false
'hi' > 'hello' // true, checks if greater alphabetically
4 >= 3 // true
Conditionals
- ==
- Equal to - doesn't have to be the same type.
- ===
- Strict equal to - must be the same type.
- !=
- Not equal to.
The difference between the first two conditionals can be show by a simple example:
3 == '3' // true
3 === '3' // false, must be of same type
3 != 3 // false
Logical operators
The logical operators AND or OR allow you to group two evaluations together. An AND evaluates to true only if both sides of the expression are true, while an OR evaluates to true if either side is true.
To get the opposite of an evaluation, use the exclamation mark (!). This will turn a false into true and vice versa.
- &&
- AND operator
- ||
- OR operators
- !
- NOT operator
!true; // false
! (3 > 3) // true
4 < 3 && 2 < 5; // true
true || false // true
Falsy and Truthy Values
It can be confusing to tell which values per data type evaluate to false
or true
. Let's go over them really quick.
Falsy values
Falsy values include the following:
var count; // no value assigned
count = false; // boolean false
count = 0; // zero
count = ''; // empty value
count = 10/'hello world!' // NaN
Truthy Values
Truthy values include the following.
var highscore = true; // true boolean
count = 1; // numbers other than 0
count = 'carrot'; // non-empty string
count = 100/20; // valid number
count = 'true'; // the string true
count = '0'; // any strings
count = 'false'; // 'false' the word as a string - non-empty
Short-circuiting values
If a value does not exist, it will evaluate to FALSE. We can take advantage of this with an OR statement
var name = 'Steven Hays';
var cadaver = (name || 'John Doe');
In this case, the cadaver will be assigned a name if it has one; otherwise, it'll be given the generic name John Doe
.
Control flow with if and switch
Using if/else
and switch
statements, we can control how code is execution.
if statement
The if
statement is closely similar to any other programming language.
Remember to NOT close any if
expression statements with a semicolon.
if (score > 10) {
alert("Congratulatiosn! You got 100%!");
} else if (score > 8) {
alert("Wow! You rocked that quiz!");
} else if (score > 7) {
alert ("You passed");
} else {
alert ("Please review your notes and try again.");
}
The alert()
is a browser object model function takes in a string and outputs it as a pop-up dialog message to the user.
Ternary if statement
You may have a ternary if
statement for cleaner code.
Take a look at the code below. The left-most statement is the conditional. If it evaluates to true
, the middle statement is executed. If false
, the right-most statement is executed.
(name == "John") ? "Hello John" : "Hello unknown person";
switch statement
If you have several else-if statements, you may want to consider using a switch
statement.
The switch
statement evaluates an expression or a given variable, then delegates the task to whichever case it matches. If no matches are found, then the default
is run.
switch (language) {
case 'en':
greeting = 'Hello world';
break;
case 'fr':
greeting = 'Bonjour le monde';
break;
case 'es':
greeting = 'Hola mundo';
default:
greeting = 'Greetings, earthlings';
break;
}
Make sure to place a break;
command after every case - otherwise JavaScript will continue to execute the next case (which is something you'll most often not want).
Loops
Loops are used to repeat a block of statements a set number of times.
for loops
When using a for
loop, you instantiate a counter variable (initialization), set a condition for the loop to run until (condition), then set some increment/decrement operator for the counter (update).
for (var i = 0; i < 10; i++) {
// code statement blocks here to run 10 times.
}
Here is a list of the steps per a for
loop:
- Initialize variable i to 0.
- Check if i is less than 10. If not, exit the loop.
- Run the code statements.
- Increment i.
- Go back to step 2 and repeat.
while loops
while
loops are similar, but the only parameter needed is the condition. Before JavaScript runs the code block within this loop, it makes sure that the condition evaluates to true.
while (i < 10) {
// Execute some commands
i += 2; // update your counter, otherwise infinite loop.
}
do-while loops
To ensure that your code runs at least once, you may use a do-while
loop. The do-while
loop first executes, then checks your conditional statement.
do {
// Execute a command block
x += 1;
} while (x < 10);
break and continue
Two extremely helpful one-word statements used exclusively in loops are break
and continue
. The former exits out of the loop, while the latter pushes the JavaScript interpreter back up to the conditional statement.