Operators
Basic operators allow you to manipulate values.
1
2
3
4
5
|
|
1
2
3
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
|
Operations on Numbers & Strings
In JavaScript, numbers and strings will occasionally behave in unexpected ways.
1
2
3
4
5
|
|
1
2
3
4
5
|
|
The Number constructor, when called as a function (as in the above example), will have the effect of casting its argument into a number. The unary plus operator also does the same thing:
1
2
|
|
Logical Operators
Logical operators allow evaluation of a series of operands using AND ( &&
) and OR ( ||
) operations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
|
In the above example, the ||
operator returns the value of the first truthy operand, or in cases where neither operand is truthy, it returns the last operand. The &&
operator returns the value of the first false operand, or the value of the last operand if both operands are truthy.
You'll sometimes see developers use these logical operators for flow control instead of using if
statements. For example:
1
2
3
4
5
6
7
|
|
This style is quite elegant and pleasantly terse; that said, it can be really hard to read or use, especially for beginners. See the section on truthy and falsy things in the Conditional Code article for more about evaluating truthiness.
Comparison Operators
Comparison operators allow you to test whether values are equivalent or whether values are identical.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|
For more information about comparison operators, visit the Mozilla Developer Network.