You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes a block of code should only be run under certain conditions. Flow control – via `if` and `else` blocks – lets you run code if certain conditions have been met.
9
10
10
11
```
11
12
// Flow control
13
+
12
14
var foo = true;
13
15
var bar = false;
14
16
15
17
if ( bar ) {
16
-
// this code will never run
18
+
// This code will never run.
17
19
console.log( "hello!" );
18
20
}
19
21
20
22
if ( bar ) {
21
23
22
-
// this code won't run
24
+
// This code won't run.
23
25
24
26
} else {
25
27
26
28
if ( foo ) {
27
-
28
-
// this code will run
29
-
29
+
// This code will run.
30
30
} else {
31
-
32
-
// this code would run if foo and bar were both false
33
-
31
+
// This code would run if foo and bar were both false.
34
32
}
35
33
36
34
}
@@ -45,31 +43,31 @@ Be mindful not to define functions with the same name multiple times within sepa
45
43
In order to use flow control successfully, it's important to understand which kinds of values are "truthy" and which kinds of values are "falsy." Sometimes, values that seem like they should evaluate one way actually evaluate another.
46
44
47
45
```
48
-
// Values that evaluate to true
46
+
// Values that evaluate to true:
49
47
"0";
50
48
"any string";
51
-
[]; // an empty array
52
-
{}; // an empty object
53
-
1; // any non-zero number
49
+
[]; // An empty array.
50
+
{}; // An empty object.
51
+
1; // Any non-zero number.
54
52
```
55
53
56
54
```
57
-
// Values that evaluate to false
58
-
""; // an empty string
59
-
NaN; // JavaScript's "not-a-number" variable
55
+
// Values that evaluate to false:
56
+
""; // An empty string.
57
+
NaN; // JavaScript's "not-a-number" variable.
60
58
null;
61
-
undefined; // be careful -- undefined can be redefined!
62
-
0; // the number zero
59
+
undefined; // Be careful -- undefined can be redefined!
60
+
0; // The number zero.
63
61
```
64
62
65
63
## Conditional Variable Assignment with the Ternary Operator
66
64
67
65
Sometimes a variable should be set depending on some condition. An `if`/`else` statement works, but in many cases the ternary operator is more convenient. The ternary operator tests a condition; if the condition is true, it returns a certain value, otherwise it returns a different value.
68
66
69
67
The ternary operator:
68
+
70
69
```
71
-
// set foo to 1 if bar is true;
72
-
// otherwise, set foo to 0
70
+
// Set foo to 1 if bar is true; otherwise, set foo to 0:
73
71
var foo = bar ? 1 : 0;
74
72
```
75
73
@@ -81,6 +79,7 @@ Rather than using a series of `if`/`else` blocks, sometimes it can be useful to
0 commit comments