Adding up the values within a range of numbers in an array using a callback function

Can you help me spot the issue in this code snippet?

function range(start, end){
  var arrayRange = [];
  for(i= start; i<=end; i++){
    arrayRange.push(i)
  }
  return(arrayRange);
}
var r = range(1,10);
console.log(r);

function sumRange(sumArray){
  var total = 0;

 for(var i=0; i <= sumArray.length; i++){
   total = total + sumArray[i];   
 }
  return total;
}

var s=sumRange(r);
console.log(s);

This is what shows up in the console.

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
NaN

I'm working on an exercise from Eloquent Javascript to grasp callback functions. My goal is to achieve this output:

console.log(sum(range(1,10)));
// 55 

Answer №1

The issue lies in the code snippet i <= sumArray.length, as the array indexes range from 0 to length -1. Therefore, the correct loop condition should be i < sumArray.length

In this scenario, during the final iteration of the loop, the result will be total + undefined, leading to a return value of NaN

function calculateSum(sumArray) {
    var total = 0;
    for (var i = 0; i < sumArray.length; i++) {
        total = total + sumArray[i];
    }
    return total;
}

You can utilize Array.reduce() method as shown below:

function calculateSum(sumArray) {
    return sumArray.reduce(function (sum, val) {
        return sum + val;
    }, 0);
}

Answer №2

In this segment of the sum function:

for(let i=0; i <= sumArray.length; i++){
  total = total + sumArray[i];   
}

The issue arises from using i <= sumArray.length as the condition instead of i < sumArray.length. This results in attempting to access an array index that does not exist, causing JavaScript to return undefined, which when combined with a number, leads to NaN.

The NaN value indicates a calculation error but lacks specificity on the exact cause. Even in strict mode, this behavior remains unchanged. Therefore, it is crucial to handle arrays carefully to prevent accessing undefined keys. Additionally, the same problem occurs when trying to access undefined object properties (as arrays are essentially objects in JavaScript).

Remember that JavaScript arrays start at index zero, meaning an array with n elements will have keys ranging from 0 to n-1. Hence, iteration should run until just before reaching the array's length using the condition

i < sumArray.length. Once this condition becomes false, it signals the end of the loop to avoid encountering undefined values.

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

Issues arise when attempting to use AngularJS validators in conjunction with another directive

I created a directive called "uniqueCheck" that validates the ngModel based on whether the value is already in a list or not. Everything works fine when the directive is used directly on an input tag. However, when used on a custom directive that contains ...

Implementing i18n in NextJS with a focus on maximizing SEO performance

My task was to implement internationalization (i18n) for our company website. Currently, we are using Netlify with @netlify/plugin-nextjs, and I encountered an issue when trying to submit a PR. An error popped up stating: Error: i18n support is not compati ...

Step-by-step guide to creating a transition effect when the input changes

I'm looking to add a unique effect to my dropdown menu My goal is to create an effect in which the placeholder moves up and the new value seamlessly takes its place, using JS, jQuery, CSS, and HTML. View before transition View after transition ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...

Issue with loading Babel preset in a monorepo setup

I'm working with a monorepo setup using Lerna and it's structured as follows: monorepo |-- server |-- package1 |-- package2 All packages in the repo make use of Babel. After installing all 3 projects, yarn copied all the required @babe ...

Press the button within the table as its name undergoes periodic changes

I am using Python along with Selenium to automate the process of selecting and reserving a room on a website. The site displays a table containing available rooms, and my goal is to locate a specific room and click on the corresponding button within the ta ...

`Inconsistencies between Postman and AngularJS service responses`

When I make a call to the endpoint using Postman, I receive this response: https://i.stack.imgur.com/pH31G.png However, when I make the same request from my AngularJS service defined below: this.login = function (loginInfo) { return $http({ ...

The use of a map with Next/image seems to be preventing the src image from loading properly

Utilizing next/image for loading images in my application has been successful, except when it comes to a carousel featuring multiple images. Whenever I attempt this, I encounter the following error: Error: Image is missing required "src" property. Make su ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...

C# Unleashed: Mastering Advanced JSON Serialization

Expanding on the concepts discussed in this article: The author discusses deserializing and serializing JSON with an array of objects but overlooks how to work with an array of objects within a request. I am looking to tackle a more complex task involvin ...

What is the method for adding items to an Eigen array or matrix?

How can an element be added to an Eigen array or matrix? By utilizing STD vector, the push_back function can be used. vector<int> index; int random = 1 + (rand() % 5); for (int i = 0; i < random; i++) index.push_back(i+i); ...

PHP unable to display HTML form element using its designated ID attribute

I've been experiencing some difficulties with PHP echoing a label element that contains an ID attribute within an HTML form. My intention was to utilize the ID attribute in order to avoid having to modify the JS code to use the name attribute instead. ...

What is the method for obtaining the worldwide location of a vertex on a skinned mesh in Three.js?

In the realm of Three.js, we've recently acquired the ability to determine the global position of a vertex in a non-skinned mesh thanks to insights from this question. Now, the query arises - how can one ascertain the global position of a vertex in a ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...

JS selection-dropbox

As someone who is relatively new to JS, I am struggling a bit. The goal of the code is to display items with specific content (ALL, A, B, C). While the code works fine with buttons, I can't seem to get it to work with a 'Dropdown-select', ...

Connected Date Selector

I am new to using Bootstrap and attempting to implement a linked datepicker with the following requirements: Display only the date (not the time). The default selected date on page load should be today's date for both the Datepicker and the text ...

Discovering the total of elements in specific locations within two arrays

Hey there! I have a question that I need help with. Given arrays A and B containing natural numbers in incremental order, along with an arbitrary natural number K, how can we efficiently find all index pairs (i, j) where the sum of elements at those indexe ...

How can I prevent a hyperlinked element from being clicked again after it has been clicked using JavaScript or jQuery in PHP

I am struggling with disabling the href after it has been clicked. Can someone please assist me with this? It is crucial for me to complete this PHP program. Style.css .disabled { pointer-events: none; } ...

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...