Control structures
In our program, we can control the flow, i.e. what happens, based on conditions. This is done using if
statements and loops.
What if?
Let's imagine that we want to print a value to the console, but only if it is not undefined. We can use the "is not equal" operator (!=) as part of an expression in an if statement:
The expression variableName != 'undefined'
will return either true
or false
, and if it is true
, the code inside the block will be executed. Should the expression evaluate to false, the block will be skipped.
Inside the parentheses you can use all the logical operators previously defined, and create complex expressions. Sometimes we need to see if a variable have a certain value:
Sometimes though, it's not enough with just one case, e.g. weather == "sun"
, so we need to ask ourselves, what else if
? This statement also takes an expression that will be evaluated to true
or false
.
The if
statement is the first to be evaluated, and if it is false
, the program will evaluate the next one, and the next one, and the next one, until it finds one that evaluates to true
. After that, it will not evaluate any more expressions in that block. If you need one "catch all" case, that should be executed should all else fail, well, JavaScript got that.
The else
block doesn't need to evaluate an expression. If no other expressions evaluate to true
, the else
block will be executed.
Using these statements will let you run different blocks of code based on the program's state, or the user's actions.
Last updated
Was this helpful?