site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

The Javascript Ternary operator

The ternary operator is a Javascript conditional statement, mainly used to declare what we want to do if a value is true or false.

The ternary operator is often used as a shorter alternative to the if else statement, it is also on one line so can also look a little simpler too.

We begin by adding a condition we want to check, such as a calculation:

10 > 5 ?

The condition is followed by the question mark, then we declare what we want to happen if the result is true or false:

10 > 5 ? 'True' : 'False'

Then we can output this simple example in a console log, or store the result in a variable:

// store result into a variable
const result = 10 > 5 ? 'True' : 'False'

// log to the console
console.log(10 > 5 ? 'True' : 'False')

// result: true

A common use for a ternary operator is to check a users logged in state, and conditionally render some content in the browser:

const loggedIn = true

const message = loggedIn ? 'Welcome back!' : 'Please log into your account to continue'

// result: Welcome back

Of course, security critical checks should be performed on the server, but this is useful for keeping parts of the UI correct, such as hiding a log in button if the user is already logged in, or changing the welcome message.

- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.