📒
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript  — this keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists — 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (‘ ’) and double quotes (“ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page
  • Starting With the Basics — The if statement
  • The Conditional (Ternary) Operator
  • Example — Driver Age
  • Example — Student Pricing
  • Example — Nested Ternary
  • Example — Multiple operations

Was this helpful?

Ternary Operator

Starting With the Basics — The if statement

Using a conditional, like an if statement, allows us to specify that a certain block of code should be executed if a certain condition is met.

Consider the following example:

We have a person object that consists of a name, age, and driver property.

let person = {
  name: 'tony',
  age: 20,
  driver: null
};

We want to test if the age of our person is greater than or equal to 16. If this is true, they’re old enough to drive and driver should say 'Yes'. If this is not true, driver should be set to 'No'.

We could use an if statement to accomplish this:

if (person.age >= 16) {
  person.driver = 'Yes';
} else {
  person.driver = 'No';
}

But what if I told you we could do the same exact thing in just one line of code? Well, here it is:

person.driver = person.age >=16 ? 'Yes' : 'No';

This shorter code yields us the same result of person.driver = 'Yes';

Now that you’ve seen the conditional ternary operator in action, we can explore how it works!

The Conditional (Ternary) Operator

First, we’ll take a look at the syntax of a typical if statement:

if ( condition ) {
  value if true;
} else {
  value if false;
}

Now, the ternary operator:

condition ? value if true : value if false

Here’s what you need to know:

  1. The condition is what you’re actually testing. The result of your condition should be true or false or at least coerce to either boolean value.

  2. A ? separates our conditional from our true value. Anything between the ? and the : is what is executed if the condition evaluates to true.

  3. Finally a : colon. If your condition evaluates to false, any code after the colon is executed.

Example — Driver Age

We’ll take a moment to revisit the initial example in this article:

let person = {
  name: 'tony',
  age: 20,
  driver: null
};
person.driver = person.age >=16 ? 'Yes' : 'No';

The most important thing to note is the order of operations. Lets add some parenthesis to help you visualize the order in which code is executing:

person.driver = ((person.age >=16) ? 'Yes' : 'No';)

As you can hopefully now visualize, the very first thing that happens is our conditional is checking to see if person.age >=16 is true or false.

Since 20 is greater than 16, this evaluates to true. Here’s where we are now:

person.driver = (true ? 'Yes' : 'No';)

Since the condition of our conditional is true, the value between the ? and : is returned. In this case, that is 'Yes'.

Now that we have our return value, the final thing to do is to set it equal to our variable:

person.driver = 'Yes';

Awesome! Now lets move on to some more complex examples.

Example — Student Pricing

In this example, we’re coding for a movie theater. The movie theatre offers two ticket prices: $12 for the general public, and $8 for students.

Lets create a variable to keep track of whether a patron is a student or not:

let isStudent = true;

With this variable we can now use a ternary operator to change the price accordingly:

let price = isStudent ? 8 : 12
console.log(price); // 8

Since our isStudent boolean is true, the value of 8 is returned from the ternary to the price variable.

Example — Nested Ternary

But what if our movie theater from above gives a discount to students and seniors?

We can nest ternary operators to test multiple conditions.

For this scenario assume tickets are: $10 for the general public, $8 for students, and $6 for seniors.

Here’s what the code for a Senior citizen would look like:

let isStudent = false;
let isSenior = true;
let price = isStudent ? 8 : isSenior ? 6 : 10
console.log(price); // 6

There’s a lot going on in this code, so lets break it down:

  1. First we check to see if our patron is a student. Since isStudent is false, only the code after the first : is executed. After the : we have a new conditional:

  2. Our second conditional tests isSenior — since this is true, only the code after the ? but before the : is executed.

  3. price is then assigned the value of 6 which which we later log to the screen.

Example — Multiple operations

It is also possible to run multiple operations within a ternary. To do this, we must separate the operations with a comma. You can also, optionally, use parenthesis to help group your code:

let isStudent = true;
let price = 12;
isStudent ? (
  price = 8,
  alert('Please check for student ID')
) : (
  alert('Enjoy the movie')
);

In the above example, the price of our movie is already set to $12. If isStudent is true, we adjust the price down to $8, then send an alert to have the cashier check for student ID. If isStudent is false, the above code is skipped, and we simply alert to enjoy the movie.

PreviousSwitch StatementNextLoops in JavaScript

Last updated 4 years ago

Was this helpful?