"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty.

function sumArray (numbers) {
  // your code

  var numbers = [1, 2, 3, 4];

if (numbers !== undefined) {
const sum = numbers.reduce((a,b) => a+b, 0)
return sum
}
else if ( numbers === []);{
  return 0
}
}
sumArray();

I attempted to handle the scenario where the array is empty by returning 0, but I seem to be missing something. Any insights would be appreciated.

Answer №1

Instead of searching for the missing code, consider simply returning the result generated by the reduce method.

return numbers.reduce((a, b) => a + b, 0);

Additional suggestions:

  • Avoid redeclaring and assigning the variable numbers, as the array is passed as a parameter.
  • Omit checking against undefined in this context, since an array is always provided as input.
  • To determine if an array is empty, do not compare it directly to another empty array. Instead, utilize the Array#length property and compare it to zero.

Answer №2

The initial problem stems from a line of code that ensures the variable "numbers" is always an array containing the values 1, 2, 3, and 4. This setup causes the condition for an empty array to never be met, making it necessary to remove that line.

Another issue arises from an unnecessary semicolon that subtly alters the logic of the program.

The current logic functions in a way that if "numbers" refers to an array created using the array literal syntax ([]), it will execute an empty statement, followed by a block that returns zero outside of the else-if block.

else if ( numbers === []);{
  return 0
}

For checking if an object is an array, use Array.isArray(foo).

To determine if an array is empty, you can check its length (if(myArray.length === 0) ...)

The corrected code you might have intended to write is:

else if (numbers.length === 0) {
  return 0
}

However, it appears that the code using "reduce" will function correctly even for arrays of zero length, rendering that logic unnecessary.

What you should aim for is something like this:

function sumArray(numbers) {
  if (!numbers) return 0;

  return numbers.reduce((a,b) => a + b, 0);
}

console.log(sumArray())
console.log(sumArray([]))
console.log(sumArray([1, 2, 3, 4]))

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

Node.js/Express API Endpoint Ceases Functioning

In my Angular/Express.js app, there is a post method within my api.service.ts file: post(data: any, endpointUrl: string): Observable<T> { console.log("REACHED POST METHOD") return this.http.post<T>(`${this.apiUrl}/${endpoint ...

problem with the visibility of elements in my HTML CSS project

How do I prevent background images from showing when hovering over squares to reveal visible images using CSS? h1 { text-align: center; } .floating-box { float: left; border: 1px solid black; width: 300px; height: 300px; margin: 0px; } div ...

Issue with activating a Modal through a button inside a table row on React

I'm currently working on two files: Modal.js and Users.js. Users.js features a table with an API get query linked to it, and in the last column of the table, there's a dropdown for each row that contains three buttons: View, Edit, and Delete. My ...

What causes my browser fingerprint to consistently remain unchanged?

declare var Fingerprint2: any; @Component({ selector: 'my-app', template: `Hello`, }) export class App { constructor() { new Fingerprint2().get(function(result, components){ console.log(result); // Device fingerprint as a hash va ...

Sending JSON-encoded data using HTML5 Server-Sent Events (SSE) is a

I have a script that triggers an SSE event to fetch json encoded data from online.php. After some research, I discovered methods for sending JSON data via SSE by adding line breaks. My question is how to send JSON through SSE when the JSON array is genera ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

Exploring Google Go Templates for Creating Dynamic Websites using Multidimensional Arrays

In my struct example, I have a two-dimensional array: type Foo struct{ testArray[9][9] int } My goal is to access it using a template. For instance: tmpl.Execute(w, foo) //foo is a pointer to Foo struct and w represents the parsed html website How can ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...

Customizing Body Color in CKEditor for Dynamic Designs

I am facing an issue with CKEditor that I am hoping to find a solution for. My scenario involves using a jQuery color picker to set the background color of a DIV element, which is then edited by the user in CKEditor. However, I have observed that it is not ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Header slide animation not functioning properly - toggles up when scrolling down and down when scrolling up jQuery issue

I'm currently experimenting with jQuery to hide the header when scrolling down and make it reappear when scrolling up, but I'm having trouble getting it to work properly. All the content that needs to be animated is within a header tag. $(docum ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Aligning a div with absolute positioning vertically

There are two elements positioned side by side: an input field and a div. The div is absolutely positioned inside a relative element and placed to the right of the input. The input field has a fixed height, while the height of the div depends on its conte ...

The information being sent from Angular is not being successfully transmitted to the XAM

Here is my Angular service post method: getUserDetails(username , password) { alert(password); return this.http.post<myData>("http://localhost/test/api/auth.php", { username, password }); } This is the structure of my PHP file: <?php ...

Express.js routes are malfunctioning with jade/pug, causing frequent crashes and routing errors

Here is the code for my contact router: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('contact'); }); module.exports = rou ...

Rendering HTML strings instead of HTML in ReactJS

When I try to display HTML, all I see is strings var ref = firebase.database().ref('raffle/'); ref.on('value', (snapshot) => { var content = ``; var IDwrapper = document.getElementById('raffleFeed'); snapshot.forEac ...