Make sure to come back inside the building only if the condition is met,

I am facing an issue when attempting to return userInput within a fat-arrow function using the conditional operator. Any suggestions are appreciated.

My code works perfectly fine in ES5;

userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors' ) {
  return userInput;
} else {
  console.log('Error!');
}
console.log(getUserChoice('Paper')); // console prints 'paper'
console.log(getUserChoice('fork')); // console prints 'Error!' and `undefined`

However, when I switch to ES6 fat-arrow syntax and the conditional operator, an error occurs. Please note: I want to immediately return the userInput once the first condition of the if..else statement is met.

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors')? return userInput : console.log('Error');
};

console.log(getUserChoice('Paper'));
console.log(getUserChoice('fork'));

The following error is displayed:

  (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors')? return userInput : console.log('Error');
                                                                               ^^^^^^
SyntaxError: Unexpected token return

Answer №1

In order to ensure clarity in the conditional statement, it is important to explicitly include the return keyword at the start. Here's an example:

return (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') ? userInput : console.log('Error'); 

Answer №2

In the realm of JavaScript, there exist two methods for diverging paths:

1) The if() statement is employed to branch out either a single statement or a block of statements.

 if(cond) {
   statement1;
   statement2;
 } else statement 3

2) Alternatively, the ternary operator can be used to branch out expressions.

 cond ? expression1 : expression2

The return keyword signifies a statement and cannot reside within an expression. You must either encompass the entire ternary operation with a return, or utilize an if statement instead.

It's worth noting that ternaries have been part of JavaScript for quite some time and are independent of arrow functions.

Answer №3

It's important to acknowledge that the ternary operator ?: functions as an operator in programming. Just like other operators such as + and *, it is used to generate a new value. Hence, placing return in your original code doesn't fit logically since return is a command (or more accurately a statement) and not a value itself.

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

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Trouble with Sum Array Function

I've encountered an issue while trying to calculate the sum of a dynamic array. Instead of adding up the numbers, they are just being displayed next to each other. I attempted to sum 1+2+3+4+5, but the output shows as 012345 instead of 15. let userIn ...

The webpage you are looking for cannot be found as there seems to be an issue with

I am attempting to pass some variables to a PHP script and then store them in a MySQL database. Below is my JavaScript code: $.ajax({ url: '/insert.php', type: 'POST', data: {endadres:endadres,stadres:stadr ...

Prevent users from selecting dates in the future using the Bootstrap datepicker

One issue I am facing is how to prevent users from selecting future dates in a form with date input. Here's the solution I came up with: $(document).ready(function(){ $('.month').datepicker({ format: 'yyyy-mm-dd', ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Encountering difficulties with managing the submit button within a ReactJS form

As I work on creating a User registration form using React JS, I encounter an issue where the console does not log "Hello World" after clicking the submit button. Despite defining the fields, validations, and the submit handler, the functionality seems to ...

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

Interface for exporting TypeScript models

I am a beginner in TypeScript and have a question regarding the code where the (position) is referencing another TypeScript model. Both models are located in the 'model' folder: export interface Group { name: string; opportunities: Opportu ...

Creating a subdocument in Mongoose involves using MongoDB along with Node.js. Here's how you

I am currently working on incorporating an array of comments as a subdocument within my main document of posts using JavaScript and Mongoose. Despite my efforts with the updateOne method, I am encountering issues when trying to use the save parameter. Addi ...

utilize jQuery to include a tag into every div

This is the current sample: <div class="main-wrap"> <div class="inner-wrap"> some example text here <span> <a href="1">test1</a> </span> </div> <div class="inner- ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

Limit search to retrieve specific items based on pointer in JavaScript using Parse.com

BlogApp.Collections.Blogs = Parse.Collection.extend({ model: BlogApp.Models.Blog, query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", "xMQR0A1Us6").descending('createdAt').limit(9) }); The code snippet above doesn't seem ...

What is your approach to managing routing within a Node and Ember application?

In my application, I am working with both Node and Ember. I have encountered a problem specifically related to routes. Both Node and Ember handle routes, but I want Node to handle certain routes and Ember to handle others. When the page initially loads, No ...

Changing the active state of an icon when clicked in a list generated by v-for in Vue

In my Vue.js application, I have created a list of objects where each object represents a star. I want to implement a feature where a star changes color when it is clicked. However, the issue I am facing is that when I click on one star, all the stars in ...

What steps can be taken to fix the eslint error related to the <p> element with the message "Non-interactive elements should not be assigned interactive roles"?

I am currently working on implementing the following code, but I have been encountering challenges in making it keyboard accessible: <p className={styles['clear-text']} onClick={clearAllFilters}> {'Clear All'} </p ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

What is the reason for the function to return 'undefined' when the variable already holds the accurate result?

I have created a function that aims to calculate the digital root of a given number. Despite my efforts, I am encountering an issue where this function consistently returns undefined, even though the variable does hold the correct result. Can you help me ...

You cannot utilize Lesson as a JSX Component in Next JS TypeScript

Below is my updated page.tsx code: import Aspects from '@/components/Aspects'; import FreeForm from '@/components/FreeForm'; import Lesson from '@/components/Lesson'; import React from 'react'; import { Route, Route ...