Ternary conditions can be used in JavaScript ES6 to quickly return

I am currently working on a function that is supposed to return an Array when the condition is true and a string when it's false. Initially, I wrote the code like this:

return (myArr != []) ? myArr : `${integer} is prime`;
However, when myArray is empty, instead of getting the output as ${integer} is prime, I receive an empty array []. When I changed it to
return (myArr.length != 0) ? myArr : `${integer} is prime`;
, it worked fine, but I am not sure why.

Below is my code:

function divisors(integer) {
  var i = 2;
  var myArr = [];
  do {
    (integer % i) ? null : myArr.push(i);
    i++;
  } while (i < integer);
  
  return (myArr.length != 0) ? myArr : `${integer} is prime`;
}

console.log(divisors(42));

Answer №1

Testing whether an array is empty by comparing it to [] is not a valid method - refer to the comments on your inquiries

Maybe you intended something like this

function divisors(integer) {
  var myArr = Array.from(Array(integer),(x,i)=>i).filter(int => integer%int===0)
  return (myArr.length>1 && myArr[0] === 1) ? myArr : `${integer} is prime`;
}

console.log(divisors(42));
console.log(divisors(11));
console.log(divisors(12));
console.log(divisors(997));

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

Guide to changing the date format from 10/04/2013 to October 4, 2013

My date is 10/04/2013 and I want to convert it to Oct 4, 2013. <input type="text" required="required" name="dateofissue" id="dateofissue" readonly> This JavaScript code retrieves the current date: var now = new Date(); document.getElementById("da ...

Remove duplicate values from ng-options

Check out this plunker example I have a collection of cars and their corresponding available years: ["Volvo", "VW", "Audi"] --> [2006, 2007, 2008] ["Ford", "Honda", "Jaguar"] --> [2008, 2009, 2010, 2011] Note: The year 2008 is duplicated. This ...

Transfer the picture file and forward it to the rest API

import { Component } from '@angular/core'; import { Http, RequestOptions, Headers, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'my-app', templateUrl: & ...

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

Tips for updating state and rendering in a function component in React Native:

I am attempting to update the state before rendering the component in a function component. While I have found suggestions to use the useEffect hook for this purpose, I am finding the information on the React official site somewhat perplexing. The docume ...

What is the best way to retrieve an id from a form and pass it to another JS file using a loop in jQuery?

Here's the current code snippet: $(data).each(function(index,worker){ if (drupal_user.uid == worker.user && comp.nid == worker.company_id){ // user is logged in and has company assigned $( '.title' ).text( comp.nod ...

switch hover interactions to click

I'm looking to change from hover to mouse click, and here is a snippet of the code: HTML <li class="has-dropdown"> <a href="#">Click Me</a> <ul class="dropdown"> <li> ...

The functionality of OnMouseOver event within CKEditor

I prefer using the CKEditor WYSIWYG editor. One issue I have encountered is with a div element that includes an onMouseOver attribute. When this element is within the editor, the onMouseOver attribute gets changed to data-cke-pa-onmouseover. Despite my eff ...

What is the best way to retrieve the object from a script file in my own JSX file?

I'm currently working with React and I'm trying to figure out how to access the object that I've included as a script in my html file from my jsx file. Here's an example snippet: <script src="url-to-some-script"></sc ...

Is there a way for me to extract the error message generated by an API request?

I am currently working on an authentication project and I am facing a challenge in displaying error messages on the screen. Specifically, I am unsure about how to show error messages such as when an email address is already registered. While I can see th ...

What are some effective methods for analyzing a minified JavaScript file within Visual Studio?

There have been numerous instances where I've received minified javascript and css files to be used in html. In similar situations in .Net, I utilize the Object Browser in Visual Studio to easily view all methods and properties along with comments, ma ...

Update the contents of a neighbor div within the same parent element using jQuery

Attempting to set the range slider value within the slider parent sibling var updateRangeSlider = function() { var slider = $('.range-slider'), range = $('.range- value = $('.range-slider__value'); sli ...

ERROR: The value property is undefined and cannot be read in a ReactJS component

Can someone help me with the error I'm encountering in the handleChange function? I'm not sure what the issue could be. const [testState, setTestState] = useState({ activeStep:0, firstName: '', lastName: '&apos ...

Attempting to navigate through nested data within existing mapped data

The data set 1 consists of an array that contains another array called data set 2. Currently, data set 1 is being mapped to display a single-column table with data1.name inside it. The data1.name serves as a clickable button that reveals the related data i ...

The international telephone input library's "grunt img" command is malfunctioning

I am currently utilizing intl-tel-input to develop a control for displaying mobile numbers. Since the flags are quite small, I am in need of enlarging them. A reference for this can be found here: https://codepen.io/jackocnr/full/ONXWgQ To achieve this, ...

When using res.json(), the data is returned as res.data. However, trying to access the _id property within it will result

I'm facing a challenge in comprehending why when I make a res.json call in my application, it successfully sends data (an order object). However, when I attempt to access and assign a specific piece of that data (res.data._id) into a variable, it retu ...

Detecting the Enter key press with jQuery event.keyCode

My combo box is filled with values, and I want to allow the user to select a value by pressing the Enter key. The user can navigate using the Arrow keys. To select a value, the user should press the Enter key. I attempted the following code: $('#c ...

When developing a multi-page application using React, encountering the error "TypeError: Cannot read property 'pathname' of undefined" may indicate an issue

I am facing an issue while trying to develop a multi-page application using react-router. As I am new to React, I find it difficult to explain the problem clearly. My goal is to incorporate a login page into the application. Suggestions and alternative app ...

Invoking an angularjs function when a text input reaches a certain length

Looking for advice on how to trigger a method in the controller only after the user has entered 'n' or more characters into a text box. Any suggestions on how to implement this functionality would be greatly appreciated! Thank you ...

Importing a JavaScript file into an Angular 2 application

Currently, I'm in the process of developing an angular2 application using TypeScript. The Situation: Within my project, there exists a module named plugin-map.ts which is structured as follows: import { Type } from '@angular/core'; impor ...