Today, I'll dive deeper into JavaScript operators.
JavaScript operators include:
- Arithmetic operators:
+
,-
,*
,/
,%
,**
- Negation operators:
-
(unary minus),!
(logical NOT) - Comparison operators:
>
,<
,>=
,<=
,==
,!=
,===
,!==
- Logical operators:
&&
(AND),||
(OR),!
(NOT) - Nullish coalescing operator:
??
- Ternary operator:
? :
Truthy and Falsy Values:
Falsy values: 0, "" (empty string), false, null, undefined, and NaN
Truthy values: Everything else
Operand
The value or variable that operators are applied to.
For example, in 5 + 2
, the numbers 5
and 2
are operands.
Unary
When an operator is applied to a single operand, it is called unary.
e.g. +5
, -x
(negates x), or typeof "123"
.
Binary
When an operator is applied to two operands, it is called binary.
e.g. 5 + 2
, x * y
Arithmetic Operators: +
, -
, *
, /
, %
, **
JavaScript implicitly converts types for operations.
For example:
5 - "3"
results in the integer 2
("3" is converted to the integer 3 to perform subtraction)
10 % "3"
results in the integer 1
Special Behavior of the +
Operator:
With strings, the +
operator concatenates them.
For example:
let value = "hello" + "world" + "!";
// "helloworld!"
This behavior differs from other arithmetic operators. The +
operator concatenates operands if either side is of type string.
For example:
"10" + 4
results in the string "104"
.
1 + 1 + "5"
results in the string "25"
(evaluated from left to right.)
Unary +
The unary +
operator converts non-numbers into numbers. It is a shorthand for Number()
.
Example:
+"123"
// 123
+ true
// 1
+""
// 0
Negation Operators:
The unary -
operator negates a number or variable, effectively flipping its sign.
Example:
let x = 3;
console.log(-x); // -3
Comparison Operators:
Comparison operators compare numbers as we know from math. For strings, JavaScript compares them based on alphabetical order or lexicographical order. You can refer to a character encoding chart (ASCII or Unicode). When performing comparisons, JavaScript converts values into numbers if necessary.
For example:
"2" > 1
// true
JavaScript has some quirks in its comparison behavior:
null == undefined
// true
null === undefined
// false
NaN == NaN
// false (NaN is defined as "not equal to any value, including itself.")
Logical Operators:
&& (AND)
The AND operator (&&
) returns true only when both operands are truthy.
true && true
// true
true && false
// false
false && true
// false
false && false
// false
JavaScript evaluates values from left to right. If the left operand is truthy, it moves on to evaluate the right operand and returns the right value.
1 && 2
// 2,
1 && true && 3
// 3
If a falsy value is encountered, it stops and returns the falsy value.
1 && null
// null,
1 && 2 && undefined
// undefined
If all operands are truthy, the last value is returned.
1 && 2 && 3
// 3
|| (OR)
The OR operator (||
) returns true if either operand is truthy.
true || true
// true
true || false
// true
false || true
// true
false || false
// false
JavaScript evaluates values from left to right. It returns the first truthy value encountered.
null || 1
// 1
undefined || 0 || 2 || 5
// 2
If none of the operands are truthy, it returns the last value.
null || undefined || 0
// 0
! (NOT)
The !
operator inverts the boolean value of the operand. It converts the operand to a boolean (true or false) and then returns the opposite value.
!true
// false
!0
// true
if (!true) {
console.log("This won't run.");
}
Nullish Coalescing Operator: ??
The nullish coalescing operator ??
was introduced more recently (ES2020). It helps handle cases where you want to check if a value is either null
or undefined
, and return a default value if so.
Syntax: let value = a ?? b;
If a
is neither null
nor undefined
, it returns a
.
If a
is null
or undefined
, it returns b
.
This operator is useful because it specifically handles null
or undefined
, without being affected by falsy values like 0, "", or false, which the || (OR)
operator would treat as falsy and substitute with the second value.
let height = 0;
alert(height || 100); // 100 (because 0 is falsy)
alert(height ?? 100); 0 (because 0 is not null or undefined)
The Modern JavaScript Tutorial
||
returns the first truthy value
??
returns the first defined value
Ternary Operator: ? :
Syntax: let result = condition ? value1 : value2;
The condition is evaluated. If it’s truthy, value1
is returned; otherwise, value2
is returned.
The Modern JavaScript Tutorial
The ternary operator is concise and often used for simple conditional assignments. For example:
const className = isActive ? "red" : "blue";
According to The Modern JavaScript Tutorial, however, using the ternary operator to execute different blocks of code (like an if statement) is not recommended. It can lead to less readable code.
let company = prompt('Which company created JavaScript?', ''); (company == 'Netscape') ? alert('Right!') : alert('Wrong.');
Instead, the equivalent if statement is more readable:
let company = prompt('Which company created JavaScript?', '');
if (company == 'Netscape') {
alert('Right!');
} else {
alert('Wrong.');
}
The ternary operator is best used for simple expressions where you are returning values, not for executing different blocks of code.
These operators are commonly used in code, and sometimes &&
and ??
can seem to produce similar results. However, they are not interchangeable. The &&
operator returns the first falsy value it encounters, whereas ??
only returns the second value if the first is null
or undefined
. It's important to carefully consider which operator to use based on the behavior you want to achieve.
Top comments (0)