From the course: Learn JavaScript: Write Modern Code with JavaScript ESNext
Unlock this course with a free trial
Join today to access over 25,000 courses taught by industry experts.
Learn about ternary operators in JavaScript - JavaScript Tutorial
From the course: Learn JavaScript: Write Modern Code with JavaScript ESNext
Learn about ternary operators in JavaScript
- The last control flow related syntax we're going to cover for the moment is something called the ternary operator. This is, again, something that many other programming languages have, but it's still worth taking a look at JavaScript's take on it. So the ternary operator is sort of like an abbreviated version of an if statement that we can use as part of larger statements. The basic syntax is like this, we have some sort of Boolean condition followed by a question mark, and then two different values separated by a colon. Now, the trick here is that if the first Boolean statement is truthy, the whole ternary statement evaluates to the first value. If it's falsey, it evaluates to the second value. Now, the nice part about this comes when we want to assign one of two different values to a variable depending on some condition in our program. Without the ternary operator, we'd have to do something like this where we define a new variable without assigning it any value, and then use an if…
Contents
-
-
-
-
-
(Locked)
Learning objectives1m 16s
-
Learn about equality in JavaScript5m 31s
-
(Locked)
Learn about if-statements in JavaScript4m 8s
-
(Locked)
Learn about for-loops in JavaScript4m 53s
-
(Locked)
Learn about while-loops and do-while loops in JavaScript1m 29s
-
(Locked)
Handle and throw errors in JavaScript2m 34s
-
(Locked)
Learn about switch-case blocks in JavaScript1m 53s
-
(Locked)
Learn about ternary operators in JavaScript1m 34s
-
(Locked)
Learn the difference between block-scoped and function-scoped variables4m 29s
-
(Locked)
-
-
-
-
-
-
-
-
-