Combining strings in JavaScript using the shorthand for plural or singular terms

$scope.message = 'Alright, you devoured ' + number + ' taco' 
      + (number.length > 1) ? 's' : '' + ', understood!';

Why does the $scope.message above only display 's'? I was anticipating tacos for plural and taco for singular using shorthand. Hm, can't seem to find where the error is.

Answer №1

It appears that additional parentheses are necessary.

The code will be correctly interpreted as

('Ok, you ate ' + num + ' hotdog' + (num.length > 1) ? 's' : '' + ', got it!')
.

Please ensure the complete conditional expression is enclosed within parentheses.

Answer №2

Rearrange the parentheses in a different way specifically for the ternary statement and extract the value of num without any additional properties.

$scope.msg = 'Ok, you ate ' + num + ' hotdog' + (num > 1 ? 's' : '') + ', got it!';

var num = 1;
console.log('Ok, you ate ' + num + ' hotdog' + (num > 1 ? 's' : '') + ', got it!');
num = 3;
console.log('Ok, you ate ' + num + ' hotdog' + (num > 1 ? 's' : '') + ', got it!');

If you have multiple words for pluralization, consider using an object and function for easier access, like this:

function getPlural(number, word) {
    return number === 1 && word.one || word.other;
}

var hotdog = { one: 'hotdog', other: 'hotdogs' },
    num = 1;

console.log('Ok, you ate ' + num + ' ' + getPlural(num, hotdog) + ', got it!');
num = 5;
console.log('Ok, you ate ' + num + ' ' + getPlural(num, hotdog) + ', got it!');

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

The HTML background color is refusing to change

I've been struggling to tweak the background color of a specific page. I attempted setting the HTML as the background color, using !important, but unfortunately, it didn't yield the desired result. The same goes for trying to set the background c ...

The slicing of jQuery parent elements

Hey there! I recently created a simulated "Load More" feature for certain elements within divs. However, I've encountered an issue where clicking on the Load More button causes all elements in both my first and second containers to load simultaneously ...

Unable to locate the script source. An internal server error 500 has occurred with the node and express-handlebars system

I'm encountering an annoying error 500 because my custom JavaScript scripts are not loading properly. I am currently running a local node.js server with express and express-handlebars. Below is my app.js file: const express = require('express&a ...

How can I locate a specific value within a multidimensional array when I already have a known value to

I am working with a multidimensional array in jQuery and I need to retrieve the conversionSI value based on a known shortname. How can I get this value and store it in a variable, or possibly display it using console.log? Could there be an optimal way to s ...

The process of enzyme shallow rendering involves the rendering of child components

Currently, I am attempting to shallow render a component in order to conduct some elementary unit tests. This particular component contains two child components that are rendered multiple times based on the parent's props. Upon querying the shallowl ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

Encountering an unexplained JSON error while working with JavaScript

I'm trying to retrieve data from a JSON API server using JavaScript AJAX and display it in an HTML table. However, I keep encountering an undefined error with the data displaying like this: Name id undefined undefined This is my code snippe ...

What is the best way to continuously add items to a div until their heights are equal?

In my layout, I have two divs positioned next to each other. Typically, the left div displays n+2 items while the right div displays n items. The value of n changes depending on the category and is already set. However, there are instances where certain ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Generating a distinct identification for a row using JavaScript

Here is my JavaScript function for dynamically adding new rows to a table in HTML. I want each row to have a unique ID. This is the code I have so far: $(document).ready(function(){ var html = '<tr><td class="cb"><inpu ...

having difficulty choosing a particular identifier from a JSON string

I'm currently working on a project to create an admin page for managing client information. However, I've encountered an issue where I am unable to select the client's unique ID to display all of their information on a separate page. On the ...

Sending data from an input field to a switch statement with dual parameters in a React application

My goal is to pass the state from a specific input field: <FormControl variant="outlined" fullWidth margin="normal"> <InputLabel htmlFor="isEbitda"> EBITDA ...

Error: Unable to access the 'create' property of an undefined value

I'm currently working on a website that utilizes Passport.js for user management. Despite being able to run my server, I encounter an issue when a user tries to submit their signup details which results in the error message "TypeError: Cannot read pro ...

Creating dynamic and asynchronous JSON structures with JavaScript

Struggling with async JavaScript here. I've got a function called within a jQuery AJAX function, and it looks like there are more async method calls in that function. Currently stuck in this situation. Here's the code snippet triggered by the jQ ...

Ways to retrieve class variables within a callback in Typescript

Here is the code I'm currently working with: import {Page} from 'ionic-angular'; import {BLE} from 'ionic-native'; @Page({ templateUrl: 'build/pages/list/list.html' }) export class ListPage { devices: Array<{nam ...

Managing POST request data in Express: A step-by-step guide

Currently, I am facing an issue with my alert button on the client side, which has an event listener that is supposed to send data to the server. Below is the code snippet for the client side: alertBtn.addEventListener("click", () => { axios ...

What is the best way to pass a model bound to a view from an ajax request triggered by clicking a button to a controller

Below is the code snippet for my AJAX call: $('#addNominationForm').on("submit", function (e) { debugger; e.preventDefault(); $.ajax({ type: 'post', url: '@Url.Action("AddNominat ...

How can array data be organized by date in an Ajax response?

i have an array with the following data [{ date: "January 2019", sum: 20, name: "Persada", },{ date: "Februay 2019", sum: 21, name: "Persada", },{ date: "April 2019", sum: 22, name: "Persada", },{ date: "January 2019", ...

Can I group data by "Month" in Tabulator JS while still retaining the full date information?

I am currently utilizing the Tabulator JavaScript library. I am aware that there is a group option available where I can group data based on certain fields in my dataset. One of the fields I have is a date field in the format MM/DD/YYYY. My objective is ...

Use jQuery to set the onclick attribute for all elements rather than relying on inline JavaScript

I am currently facing a challenge with converting inline JS to jQuery. My goal is to eliminate all inline onclick events and instead target them by class. HTML - checkbox <td class="center"> <?php if ($product['selected']) { ?> ...