Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3327

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T01:41:12+00:00 2024-11-26T01:41:12+00:00

Demystifying the Ternary Operator in JavaScript

  • 61k

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; 
Enter fullscreen mode Exit fullscreen mode

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; 
Enter fullscreen mode Exit fullscreen mode

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

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

Ternary operator in demonstration

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;  
Enter fullscreen mode Exit fullscreen mode

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>  
Enter fullscreen mode Exit fullscreen mode

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

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!

javascriptprogrammingreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.