JavaScript’s conditional operators are like those in most C/C++ styled languages.
Assume that x = 5 in the series of statements below:
Operator | Description | Comparing | Returns |
---|---|---|---|
== | equal to | x == 7 | false |
x == 5 | true | ||
x == “5” | true | ||
!= | not equal to | x != 8 | true |
x != 5 | false | ||
> | greater than | x > 5 | false |
>= | greater than or equal | x >= 5 | true |
< | less than | x < 5 | false |
<= | less than or equal to | x <= 5 | true |
JavaScript gives two additional conditional operators to force the checking of type, along with the checking of values. These are commonly known as strict comparisons.
Operator | Description | Comparing | Returns |
---|---|---|---|
=== | equal value and equal type | x === 7 | false |
x === 5 | true | ||
x === “5” | false | ||
!== | not equal value or not equal type | x !== 7 | true |
x !== 5 | false | ||
x !== “5” | true |
Traditional Conditions
Traditional conditional statements are the same in JavaScript as they are in other C style languages. You have the if keyword, your condition, and then your true block, in optional braces if one line, and required braces for multiple lines.
if ( <condition> ) {
// true block
}
These of course can be nested, and have an optional else
clause.
if ( <condition> ) {
// true block
} else if ( <condition 2> ) {
// true block
} else {
// else block of code
}
Ternary Operator
JavaScript supports the ternary operator ?
This puts the condition on the left, and simple true false statements on the right. The general case is below.
<condition> ? <true statement> : <false statement>
So it might look like:
let age = 15;
age > 16 ? text = "old enough to drive"; : text = "too young to drive";
console.log(text);
Nullish Coalescing
What if you wanted to check to see if a value was null (or undefined), and change it’s value if it was, but leave it if it wasn’t?
Imagine an issue like:
if( x === undefined ) {
x = 3;
}
Well, that’s what nullish coalescing is designed to do, simplifying it to ?? (a double question mark). So the same code would be:
x = x ?? 3; // set x to 3 if it doesn't have a value.
This makes this code easier to read and faster to write, with fewer potential areas for mistakes. This isn’t unique to JavaScript, as several modern languages have this feature, but many languages do not, so it is good to learn.
JavaScript Conditions was originally found on Access 2 Learn
3 Comments
Comments are closed.