I am looking to grasp the concept of the Conditional ternary statement

I attempted to convert the code below into a ternary operator, but unfortunately ended up with an undefined result. Could someone please clarify where I made a mistake and advise on how to correct it properly? Thanks in advance.

const plantNeedsWater = function (day) {
  /*if (day === 'Wednesday'){
    return true;
  } else {
    return false;
  }*/
  (day === 'Wednesday') ? true : false
  return
}

console.log(plantNeedsWater('Tuesday'));

Answer №1

When a function contains a simple plain return; statement, it will return undefined rather than a primitive Boolean.

There is no need to use a ternary operator in this case; you can simply return the evaluation directly.

const plantNeedsWater = function (day) {
  return day === 'Wednesday';
}

console.log(plantNeedsWater('Tuesday'));   // false
console.log(plantNeedsWater('Wednesday')); // true

You can also write this in an ES5 style using an Arrow Function with implicit return:

const plantNeedsWater = (day) => day === 'Wednesday';

If you prefer to use the Conditional (ternary) Operator, you can do so to return non-Boolean values as shown below:

const plantNeedsWater = function (day) {
  return day === 'Wednesday' ? "yes" : "no";
}

console.log(plantNeedsWater('Tuesday'));   // "no"
console.log(plantNeedsWater('Wednesday')); // "yes"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

Issue: ReactJS + MaterialUI + TypeScript - Property 'component' does not exist?Possible error in ReactJS: component property is

Currently, I am designing my own custom typography. However, I have encountered an error while implementing it. I have been referring to the following documentation: https://mui.com/material-ui/api/typography/ Here is the code snippet that I am using: h ...

Can an input element be used to showcase a chosen image on the screen?

I would like to display the selected image from an input element. Can this be done with a local file, accessing the image on the client side, or do I need to upload it to a server? Here is my React code attempt: I can retrieve the correct file name from t ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

Improved method for categorizing items within an Array

Currently working on developing a CRUD API for a post-processing tool that deals with data structured like: { _date: '3/19/2021', monitor: 'metric1', project: 'bluejays', id1: 'test-pmon-2', voltageConditio ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Troubleshooting issue: JSON object is returning undefined despite its presence in NASA API integration with ReactJS

{this.imageRenderer(item.data[0].media_type, item.links[1], item.links[0])} When trying to access item.links, it shows as undefined even though it is present. (Data is retrieved from NASA API) Image: As seen above, the links attribute exists. I am puzzle ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

What do you call the syntax %< ... >%?

Observed zoomInAnimation : true, zoomOutScale : false, templateLegend : "<ul class=\"<%=type.toLowerCase()%>-legend\"><% for (var j=0; j<sections.length; j++){%><li><span style=\"background-color:<%=section ...

What could be causing this function to malfunction?

Apologies for any inaccuracies in technical terms used here. Despite being proficient in English, I learned programming in my native language. I am currently working on a project using the latest version of Angular along with Bootstrap. I'm unsure if ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

How to execute a system command or external command in Node.js

I am encountering an issue with Node.js. When using Python, I would typically perform an external command execution like this: import subprocess subprocess.call("bower init", shell=True) Although I have explored child_process.exec and spawn in Node.js, I ...

The combination of Firebase Storage's listAll() method and getDownloadURL() function is not functioning properly

I created a function in my utils file that is designed to find and retrieve the URLs of images stored within a specific folder on Firebase Storage. The folder path is "proj_name/screenshots/uid/" and it contains 8 images. I have imported this function into ...

Clicking on a Vuetify v-btn with the :href attribute set to download will open the XML file

I'm having trouble getting the v-btn to download an XML file instead of opening it in the browser. <v-btn :disabled="!exportUrl" block x-large height="100" color="primary" :href="exportUrl" download> ...

What could be causing a tooltip to remain visible even after a mouseleave event in a React application

My goal is to display a tooltip when the mouse enters an item, and hide it when the mouse leaves. I created a demo that works perfectly fine. Check out the working demo here The above code successfully shows the tooltip on hover and hides it on leave. I ...

Issues are arising with the for loop in an express node js app using ejs, as it is not displaying the intended data and

I am currently utilizing a for loop in JavaScript to display all the users from the database using ejs. I have included the code snippet below. This is within an express/node js application where SQL is used for data storage. <div class = "Contacts ...

Postpone an automatic action in React

I'm currently working on adding a fade out animation to a page change in React, but I need to delay the click event before the page actually transitions. Here's the code snippet I have so far: export default function Modal({setTopOf}) { const ...

I would greatly appreciate any recommendations on how to troubleshoot and

I've been working on the "Map the Debris" challenge at freecodecamp, and I'm facing an issue. While my code works fine in my PC's editor, it doesn't satisfy the conditions when I paste it into the website area. Any suggestions on how t ...