DEV Community

Ray
Ray

Posted on

React: Template Literals & Ternaries Instead of if/else Statements

This week we continue our React study notes, and this week I've learned two simple but very useful uses: Template Literals & Ternaries Instead of if/else Statements.

Continue to use the book model used in the first two study notes. First, we create a simple summary, in defining an object we can use the Template Literals

`${js or element's own attributes}`
Enter fullscreen mode Exit fullscreen mode

JavaScript can be used inside to achieve the effect we wish to print! Eg:
Image description

For example, we want the printed String to determine whether the book object has the property 'hasMovieAdaptation', where we use the judgment

${hasMovieAdaptation ? "(if true)" : "(if false)"}
Enter fullscreen mode Exit fullscreen mode

See, the output changed
Image description

Now let's take this simple judgment and add a little bit of new conditions, such as for the number of pages to be judged.

pages > 1000 ? "over 1000": "less than 1000";
Enter fullscreen mode Exit fullscreen mode

But every time you need to print when writing such a long judgment is always inconvenient, then we try to define this judgment as an object, like this:

Image description

You can see that our log successfully prints out the result of the desired judgment.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →