DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

I've reorganized the ternary operator (?:) so it can be used in TypeScript too!

Introduction

While building an app with React and Supabase,
I encountered a situation where I wanted to display a link only under certain conditions.

At first, I was using if/else, but then I remembered the ternary operator (?:).

I'd like to recap the ternary operator (?:).

What is the ternary operator?

The syntax is simple:

Condition ? True : False
Enter fullscreen mode Exit fullscreen mode

Example: GitHub URL case analysis
Standard if/else

let githubUrl;
if (user.github_id) {
githubUrl = `https://github.com/${user.github_id}`;
} else {
githubUrl = null;
}
Enter fullscreen mode Exit fullscreen mode

Using the ternary operator...

const githubUrl = user.github_id
? `https://github.com/${user.github_id}`
: null;
Enter fullscreen mode Exit fullscreen mode

Useful in JSX

The ternary operator is also useful for toggling visibility.

{githubUrl ? (
<a href={githubUrl} target="_blank">GitHub</a>
) : (
<p>Not registered</p>
)}
Enter fullscreen mode Exit fullscreen mode

Summary

I had forgotten some grammar, so I'd like to review it again.

Top comments (0)