-
Notifications
You must be signed in to change notification settings - Fork 24
Conditionals
Rohan Singh edited this page Apr 21, 2019
·
17 revisions
Conditionals operate on bool
values, but other values can implicitly convert to a bool
value. The following table shows how this conversion takes place.
Type | Converts To |
---|---|
number |
true if not NaN
|
string | true |
object | return value of [[__bool
|
array | true |
null | false |
undefined | false |
function | true |
for (var i = 0; i <= 5; i++) {
if (i == 1) {
print('one');
} else if (i == 2) {
print('two');
} else if (i == 3) {
print('three');
} else if (i == 4 || i == 5) {
print('four or five');
} else {
print('something else');
}
}
The break
statement can be used in branches to exit the switch statement. Branches do not allow fallthrough and have an implicit break
before other cases.
for (var i = 0; i <= 5; i++) {
switch (i) {
case 1:
print('one');
case 2:
print('two');
case 3:
print('three');
case 4:
case 5:
print('four or five');
default:
print('something else');
}
}
The ternary operator (?:
) is a conditional expression that is like an inline if
..else
block. The ternary operator can be used like this:
var a = 5;
var b = a >= 3 ? 10 : 0;
The same thing can be accomplished by doing this:
var a = 5;
var b;
if (a >= 3)
b = 10;
else
b = 0;