Conditions provide a simple but powerful way to control the flow of code execution. Loops allow you to perform repetitive operations with less code. Let's take a look at:
if
conditionsswitch
statementswhile
,do-while
,for
, andfor-in
loops
Note
The examples in the following sections require you to switch to the multiline Firebug console. Or, if you use the WebKit console, use Shift + Enter instead of Enter to add a new line.
Here's a simple example of an if
condition:
var result = '', a = 3; if (a > 2) { result = 'a is greater than 2'; }
The parts of the if
condition are:
The
if
statementA condition in parentheses—"is
a
greater than 2?"A block of code wrapped in
{}
that executes if the condition is satisfied
The condition (the part in parentheses) always returns a Boolean value, and may also contain the following:
A logical operation:
!
,&&
, or||
A comparison, such as
===
,!=
,>
, and so onAny value or variable that can be converted to a Boolean...