Can someone help me figure out where I'm going wrong with the JS ternary conditional operator

Looking to improve my JavaScript logic skills as a beginner. Appreciate any tips or feedback on the function and not just this specific question.

I'm curious why the code outputs --> [3,5]

function divisors(integer) {
  let divisors = []
  for (let i = 2; i < (integer/2); i++){
    if (integer % i === 0){
      divisors.push(i) 
    }
  }
  return divisors 
};

divisors(15)

However, the following code returns True:

function divisors(integer) {
  let divisors = []
  for (let i = 2; i < (integer/2); i++){
    if (integer % i === 0){
      divisors.push(i) 
    }
  }
  return divisors ? divisors != [] : 'test${interger} is prime'
};

divisors(15)

This is what I am trying to achieve:
return divisors if divisors != [] else f'{integer} is prime'

If you could break down what's happening between these two sets of code, that would be really helpful!

Answer №1

The ternary operator is composed of three sections:

condition ? true value : false value

Your initial statement was:

divisors ? divisors != [] : 'test${interger} is prime'

In this case, the condition being evaluated is divisors (i.e. Is divisors a true value).

If it is, the result will be divisors != []. The != comparison returns a boolean. Since no value can match an empty array, divisors != [] will always be true.


This is what I am aiming to express: return divisors if divisors not equal to an empty array otherwise display '${integer} is prime'

However, there are three issues with your approach:

  • The condition needs to come first
  • As previously mentioned, comparing divisors to a new array will always yield true. To check for an empty array, you need to assess its length.
  • Template strings should be enclosed in backticks (`), not single quotes (')

Therefore, the correct syntax would be:

divisors.length > 0 ? divisors : `test${interger} is prime`

You can simplify divisors.length > 0 to just divisors.length since 0 evaluates as false and any other number as true.

Answer №2

However, the code below will result in True

This outcome is derived from the following operation:

divisors ? divisors != [] : 'test${interger} is prime'

If divisors holds a value that is considered to be true, then the expression will evaluate to true. If not, it will resolve to the string 'test${interger} is prime'.

Your intention appears to be returning divisors if it is not empty, and returning a specific string otherwise. In this case, you could check the array's length directly and return the array itself instead of comparing it with an empty array. For example:

divisors.length > 0 ? divisors : 'test${interger} is prime'

Furthermore, if the string is supposed to be a template literal, different quotes should be utilized:

divisors.length > 0 ? divisors : `test${interger} is prime`

It's worth noting... This does not qualify as a "single line if statement". It is actually a conditional expression using the ternary operator. Despite their similar functionality, a ternary conditional expression and an if statement or block should not be treated interchangeably.

Answer №3

From my understanding, you are looking to identify the divisors of a given integer, specifically 15 in this case.

The divisors of 15 are [1, 3, 5, 15], which should be the expected output.

However, it seems that there is an issue with how the loop iteration is starting at 2 and ending at half the integer, excluding both 1 and the integer itself as potential divisors.

As a result, you are only left with the divisors 3 and 5 in your current calculations.

In regards to the second part:

Your ternary statement checks if there are any values in the variable "divisors." If there are values present (such as [3, 5]), the condition returns true.

This leads to the function outputting True based on the mentioned conditions.

Here's a suggestion for what you might want to achieve:

return divisors != [] ? divisors : f'{integer} is prime'

The above ternary statement evaluates whether there are divisors present or not. If divisors exist, it returns those values; otherwise, it returns a string indicating that the integer is prime.

Please feel free to reach out if you need further clarification or assistance on this matter.

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

I have noticed that the baseline of a Span element has shifted after updating my Chrome browser to a version that begins with

Once I updated to chrome Version 108.0.5359.94 (Official Build) (64-bit) from 107.0.5304.87 (Official Build) (64-bit), the behavior of the span element changed drastically. It shifted its baseline when multiple spans were stacked on top of each other. Exp ...

Understanding Vue.js: Effectively communicating updates between parent and child components using scoped slots

My goal is to develop a component with two slots, where the second slot repeats based on the number of items in the first slot. I have successfully implemented this using scoped slots. However, I noticed that when the data in the first slot is updated, the ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

I want to display a background color using this ng-template

enter image description hereMy code includes an ng-template that uses ngFor to generate internal HTML tags without the ability to add CSS properties. <ng-template *ngFor="let c of colors" contextMenuItem let-item (execute)="change_task_color($event.ite ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

Making changes to the res object in an Express.js application

I came up with an innovative idea for the backend design of my single-page application website. My plan is to configure it so that any routes starting with "/api/" will return only the necessary data in JSON format, while all other routes will trigger a fu ...

Conceal a div element after initial visit

There is a button (B) that displays a menu (C) when clicked, and a pop-up (A) that also shows the same menu (C) when clicked. There are 4 tasks to accomplish here. 1) Clicking B reveals C. 2) Clicking A reveals C. 3) Clicking B hides A. 4) A should be hi ...

Is there a way to effortlessly refresh the WooCommerce cart and receive updated HTML content all in one go?

I am currently working on a customized "mini-cart" that mimics the functionality of the main cart page, including options to adjust quantity, remove items, enter coupons, and remove coupons. I have set up the cart to submit changes via Ajax by listening fo ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Child object in Three.js does not inherit transformation from its parent

Consider a scenario where there is a main object with multiple child objects in a given scene. Update: Here is the code snippet for creating a mesh (assuming the scene and camera are already set up). Code snippet for creating the parent group: var geome ...

The text is not displaying as expected due to a timeout issue

Trying to create a pop-up that functions as follows: After 3 seconds, the close button should appear, but during those 3 seconds, there will be a countdown. However, I'm encountering an issue where no text is being displayed. var n = 3; function p ...

Updating and deleting Firebase data from an HTML table: A guide

I am struggling to make the onClick function work in order to update and delete already retrieved data from an HTML table view. Despite trying different approaches, I can't seem to get it right. var rootRef = firebase.database().ref().child("prod ...

Achieve horizontal bar movement by utilizing google.visualization.DataTable in a left-to-right motion

I am exploring the possibility of reversing the direction of a chart(bar) using google.visualization.DataTable. In the current setup, the bar progresses from left to right, but I wish for it to move from right to left instead. Below is what I have attempte ...

Guide on how to initiate a file download with text area content by clicking an HTML button

I came across this code snippet on GeeksforGeeks, and it partially solves an issue I was facing. <script> function download(file, text) { //creating an invisible element var element = document.createElement('a'); ...

Title: "Customizing Labels on Stack Bars and Lines in D3.js Visualization"

Currently working on a stacked bar chart with a line chart on dual axis using D3.js and facing difficulty aligning labels correctly. Check out the code I have experimented with so far: https://plnkr.co/edit/doobXBC5hgzvGwDLvArF?p=preview I am looking to ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

JavaScript objects and AJAX versus ASP MVC3 Model: A comparison of client-side and server

As someone who is still learning about MVC, I find myself a bit unsure about the best way to integrate MVC models with JavaScript objects and AJAX. For instance, in one of my applications, I have a calendar that displays user events stored in a database. ...

Refresh a table using jQuery Mobile, PHP, and AJAX without having to reload the entire page by clicking a

Currently, I am working on a web app that includes a pop-up feature. When the user clicks on the pop-up to close it, I want the table data to refresh without having to reload the entire page. This pop-up allows users to modify existing data in the table. A ...

Understanding the process of linking JavaScript code to a database within the ASP.NET framework

I have been successfully using an ASP.NET application to connect to a SQL Server 2016 database. However, I now have a new task of incorporating Javascript into the code in order to retrieve data from the database and present it to the user. I am aware of t ...

What factors contribute to the poorer performance of SVG rendering compared to PNG rendering?

I conducted a comparison of two images across various browsers. One image is an SVG while the other is a PNG format. Here are my findings: You can view the demo on JSFiddle here: http://jsfiddle.net/confile/2LL5M/ This is the code snippet I utilized: ...