Demystifying the Ternary Operator in JavaScript
Tags: javascript, webdev, programming, react
Published: 2023-09-27 16:37:55

Have you ever wondered if we can remove that curly brackets that comes with **if and else** statement? Or you wish if you can just use it inside your jsx (if you use React js) without writing any function?

Ternary operator will help you achieve the same result, you can write simple conditional logic in one line, yes one line 😊. Ternary operator will also help you to write conditional codes in your jsx. Ternary operator will help you write clean and efficient codes as a developer.

In this article, we will understand what is ternary operator, it`s syntax and how to use it.

**Prerequisites you need to understand this article**

1. Basic understanding of HTML,CSS and JavaScript

2. Basic knowledge of any JavaScript framework like React js

3. A web browser like Google Chrome


**What is Ternary Operator**

Ternary operator is a concise conditional operator in Javascript, that allows developers to write conditional statements in a single line of code. Ternary operator makes developers` code more readable and clean.

**Syntax**

Ternary operator is made up of the condition, the logic that will be implemented if the condition is true, then the logic that will be implemented if the logic is false.

```
condition ? expression_if_true : expression_if_false;
```

**Example**

```
import React from 'react';

class MyComponent extends React.Component {
  render() {
    const isLoggedIn = true;
   

    return (
      <div>
        <p>{isLoggedIn? "We have a user" : "No user"}</p> 
      </div>
    );
  }
}

export default MyComponent;
```
From this simple code, I am checking if the variable isLoggin is true or false, if it`s true our p tag will display "We have a user", like this 


![Ternary operator in demonstration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvzj41ize6qou6a3jstc.png)

If the variable is false then our p tag will display "No user", it`s very simple.

![Ternary operator in demonstration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzm1uh9utvizj3teojer.png)

Here is a more complex example

```
import { useState } from "react";
import products from "./DemoCartMenuData";
import { useContext } from "react";
import { Link } from "react-router-dom";
import  {CartContext}  from './Context';
import StarBorderIcon from '@mui/icons-material/StarBorder';

const DemoCartMenu = () => {
    
    const {addToCart}   = useContext(CartContext);
    const {cartItems} = useContext(CartContext);

    const {errorMessage}= useContext(CartContext);
   
    const [items, setItems]= useState(products);
   
    const cheapItemFisrtFunction=(price)=>{
        const cheapItem15 = products.filter((itemP)=> itemP.price <= price)
        setItems(cheapItem15)
    }
    const cheapItemSecondFunction = (price)=>{
        const cheapItem20 = products.filter((itemP)=>itemP.price >= price)
        setItems(cheapItem20)
    }
    const cheapItemThirdFunction = (price)=>{
        const cheapItem30 = products.filter((itemP)=> itemP.price >= price)
        setItems(cheapItem30);
    }

    const cheapItemFourtFunction= (price)=>{
        const cheapItem40 = products.filter((itemP)=> itemP.price >= price)
        setItems(cheapItem40)
    }
    const fullProducts = (prod)=>{
        if(prod === "all"){
            setItems(products)
        }
    }

    const changeBtnBg = (e)=>{
        
    const buttons = document.querySelectorAll('.filter-btn');

    buttons.forEach((button) => {
        button.classList.remove("active");
    });

    e.target.classList.add("active");
    }

    return ( 
        <section className="product-section">
            <h3>Filter products by price</h3>
            <div className="filter-btn-con" onClick={changeBtnBg}>
            <button onClick={()=>cheapItemFisrtFunction(15)} className="filter-btn">💲15 below</button>
            <button onClick={()=>cheapItemSecondFunction(20)} className="filter-btn"> 💲20 and above </button>
            <button onClick={()=>cheapItemThirdFunction(30)} className="filter-btn"> 💲30 and above </button>
            <button onClick={()=>cheapItemFourtFunction(40)} className="filter-btn"> 💲40 and above </button>

            <button onClick={()=> fullProducts("all")} className="filter-btn">All</button>
            </div>
   
           
            <div className="items-grid-con">
            {
                items.map((item)=>{
                    return(
                        <div className="item-con">
                            <Link to={`/ItemDetails/${item.id}`}>
                            <div className="img-con">
                                <img src={item.img} alt={item.name} />
                            </div>
                            </Link>
                            <div className="item-details-con">
                            <div className="item-price-name-con">
                                <p>{item.name}</p>
                                <p> 💲{item.price}</p>
                            </div>
                            <div className="item-rating-con">
                            <StarBorderIcon className="rating"/> <StarBorderIcon className="rating"/><StarBorderIcon className="rating"/><StarBorderIcon className="rating"/>

                            </div>
                            
                            //this code here
                            <button onClick={()=> addToCart(item)}>
                                { cartItems.find((tem)=> tem.id===item.id)?"Item is in cart":"Add to cart"}</button>
                            </div>

             
                            

                        </div>
                    )
                })
            }
            </div>
                       
        </section>
     );
}
 
export default DemoCartMenu;
                            
```
If you check the code above, you will see this small piece of code

```

<button onClick={()=> addToCart(item)}>{ cartItems.find((tem)=> tem.id===item.id)?"Item is in cart":"Add to cart"}</button>
                            
```
This code checks whether any of the items I am rendering has been added to the cart or not. If the id of the products matches with any id of an item in the cart, the button will display "Item is in cart" if not, the button will display "Add to cart". Click this link to watch a simple demonstration of what I am trying to explain [Link](https://screenrec.com/share/Hn6Zbj1wqY)

**NOTE** This is one of my old e-commerce project.

Now that you have understood what ternary operator is, how to use it, when to use it and why you should use it. You can now go ahead and build amazing applications with your newly acquired super power 😊.

**Conclusion**
Ternary operator is a concise conditional operator in JavaScript, that enables developers to write clean and readable codes. It only takes one line, it also allows you to implement simple logic in your jsx.

I believe you now understand what a ternary operator is and why you should use it.

Please if you have any question let me know in the comment section I will reply to your questions. Please don`t forget to like this article for other developers to see it. 

Happy coding!