Trouble with ternary operator within array .find() method in JavaScript

I came across a puzzling scenario while using a ternary operator within the .find method of an array. In my search for an object:

Consider this:

const list = [
  { id: 1, name: "dave"},
  { id: 3, name: "choi"},
  {id: 4, name: "bob"}
]

// this works
let isBoy = true
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))


// this don't work
isBoy = false
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))

// this always works: use () around ternary
console.log(list.find(v => v.name === (isBoy ? "dave" : "choi")))
isBoy = true
console.log(list.find(v => v.name === (isBoy ? "dave" : "choi")))

What surprised me was that

// this don't work
isBoy = false
console.log(list.find(v => v.name === isBoy ? "dave" : "choi"))

It will return "dave" instead of "choi". This led to a very challenging bug to locate today. Can anyone explain what exactly is happening here and why it behaves like this?

Why do parentheses make a difference? What resources should I refer to in order to grasp this concept better? Is it related to the order of operations? My javascript IDE linter did not indicate any issue or warning, which it usually does with similar precedence matters.

My Attempts

I attempted to find similar SA queries that could provide insights into this issue but could not find an explanation for what puzzled me.

Answer №1

The issue lies in operator precedence. Comparison operators take priority over ternary operations (since comparisons are often used in the condition), causing your code to be interpreted as:

list.find(v => (v.name === isBoy) ? "dave" : "choi")

To achieve the desired outcome, you must include parentheses like this:

list.find(v => v.name === (isBoy ? "dave" : "choi"))

Answer №2

Ah, yes,

It all boils down to the sequence in which JavaScript code is executed,

v.name === isBoy ? "dave" : "choi")

In essence, this translates to

if ( v.name === isBoy ) {
  return "dave"
} else {
  return "choi"
}

Answer №3

One of the challenges lies in ensuring that the function embedded within .find() produces a boolean outcome. In the initial two instances, the outputs are not boolean - rather than returning true or false, they yield 'dave' or 'choi'. Consequently, the system interprets whichever result is generated as truthy, causing the .find() query to consistently retrieve the first item in the list. By modifying your code to read

console.log(list.find(v => v.name === (isBoy ? "dave" : "choi")))
the issue is resolved since the embedded function now consistently returns a boolean value: if isBoy===true, it confirms v.name==="dave"; otherwise, it verifies v.name==="choi".

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

Generating a dropdown menu using JavaScript from a JSON data source

I'm having trouble figuring out how to approach this task. What I want to do is generate multiple select inputs dynamically, each with different options but sharing a common set of choices. Let's say I have the following data in a JSON file: da ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

Scrolling smoothly with React-Leaflet

In my React-Leaflet project, I am aiming to implement a seamless zoom effect. I am aware that vanilla Leaflet supports this feature, as mentioned in this post, utilizing smoothWheelZoom. However, considering the compatibility issues between vanilla Leafle ...

The initial state in Next.js does not support accessing localStorage

I'm currently working on a project using Next.js along with Redux Toolkit. Initially, I attempted to utilize localStorage, but encountered the issue 'localStorage is not defined'. As a result, I switched to using cookies-next, only to face a ...

Refresh the HTML page following a jquery click event

One of my onclick functions is designed to return sorted data in a specific format when triggered. Here's the code snippet for this function: $(document).ready(function () { $(".feedbackClick").click(function () { $.post("/Analyze/GetSorte ...

Incorporate a share (contact) feature for WhatsApp and various messaging platforms on your website

Is there a way to include a share button on my website's page? I found that we can add a send SMS feature to mobile HTML pages using the following code: <a href="sms:?body=...">title</a> How can we implement this code for sharin ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

How can you set up an event listener for multiple keys in a React application

I'm trying to implement an event listener that detects when the command+c keys are pressed to copy something to the clipboard. However, I want to listen for multiple keys at once. I attempted to use useState, useEffect, and document.addEventListener, ...

ng-repeat and $scope problem

I am having an issue with my page where I display 3 images in a row using Ng-repeat. When I click on any image, it only shows the first image that was displayed in that particular row. Template: <div id="galscrolldiv" class="row" ng-repeat="image in i ...

I am being thrown an npm ERR! by Heroku because it says there is a missing script called "start"

I'm facing issues while trying to deploy a simple app on Heroku. The application keeps crashing and these errors keep popping up. In my setup, I have included: "start": "node app.js", The Procfile also contains the command &a ...

During the npm process, packages are automatically included in the project

I have encountered a strange problem with npm. I attempted to run - npm install cookie-parser and the result is - <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed99889e99addcc3ddc3dd">[email protected]</a> /ho ...

What is the best way to arrange objects within an array based on a specific element contained in another array of objects?

Suppose we have two arrays of objects named per and con. The goal is to sort the per array in ascending order based on the continent values from the con array. How can we achieve this? By using the sort and find functions exclusively. Below is the code sni ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

JavaScript event target compatibility with IE8

Similar Question: Javascript IE Event The script I have written is causing issues specifically in IE8, while working fine on all other browsers. The error message I am seeing is: 'tagName is null or not an object'. Even though I am aware tha ...

Acquiring JSONP using Angular.js

<html ng-app="movieApp"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/an ...

A guide to setting properties using a Proxy object

Within my class, I have included a Proxy which is structured as follows: export class Row<T extends ModelItems> { private _row: T = <T>{} public constructor(rowItems?: T) { if (rowItems) { this._row = rowItems } return new Proxy( ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

The issue at hand is that the headers cannot be redefined once they have already been sent

Hello, I have tried numerous solutions but have not been able to resolve the "Can't set headers after they are sent" error in the following simple code. I have spent several days working on this and would greatly appreciate any input you may have. ap ...

Is there a way to access the value of a variable in Express that is stored in a different file?

Looking for a way to fetch the value of a variable that is located inside app.use? chatbot.js: const express = require('express'); const app = express.Router(); app.use(['/chat', '/chatbot'], (req, res, next) => { const ...

Is it necessary to run npm install when a package does not have any dependencies?

If I have an npm package that contains all its dependencies bundled into one file using webpack, and I unpack it into the directory ./my-awesome-package/, should I still run npm install ./my-awesome-package/? I am aware of being able to specify preinstall ...