Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes

Quizzes

Lesson 3, Topic 8
In Progress

JavaScript: Ternary Operator

Yasin Cakal 2 Nov 2021
Lesson Progress
0% Complete

We can use a ternary operator to simplify an if…else statement in the spirit of using short-hand syntax.

Consider the following example of an if…else statement:

let isSaturday = true;
 
if (isSaturday) {
  console.log('Weekend is here!');
} else {
  console.log('Week is still going!');
}

//Output: Weekend is here!

To get the same result, we can use a ternary operator:

let isSaturday = true;
isSaturday? console.log('Weekend is here!') : console.log('Week is still going!');

//Weekend is here!

In the above example:

  1. Before the ?, there is a condition called isSaturday.
  2. After the ?, there are two expressions separated by a colon :.
  3. The first expression is executed if the condition evaluates to true.
  4. The second expression is executed if the condition evaluates to false.
  5. Ternary operators, like if…else statements, can be used for conditions that evaluate to true or false.

Responses

Leave a Reply

%d bloggers like this: