Encountering null values when summing using the reduce method in JavaScript

I attempted to create two functions with the same name, one that required a starting point and another without one. However, I encountered an issue where the function without a start point resulted in NaN.

function sum(array,start){
  return array.reduce((result, item) => result + item,start);
}
console.log(sum([1,8],8))

function sum(array){
  return array.reduce((result, item) => result + item);
}

console.log(sum([1,8]))

Answer №1

Function overloading is not a built-in feature in JavaScript, but you can achieve similar functionality by using default parameters. For example:

function sum(array,start = 0)
{
  return array.reduce((result, item)  => result + item, start);

}
 
console.log(sum([1,8],8))
console.log(sum([1,8]))

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

Achieving inline behavior for two divs using React

// Custom JavaScript code const hookFunction = () => { const {useState, useEffect} = React; const Slider = props => { const { innerWidth: width, innerHeight: height } = window; const urls = [ "https://www.imb. ...

What are some ways to blend arrays and objects in Javascript?

Input Array: [{name: xyz}, {name: abc}, {name: def}], [ {name: ghi}, {name: jkl} ] Desired Output: New Array: [{name: xyz}, {name: abc}, {name: def}, {name: ghi}, {name: jkl}] ...

Incorporating an iFrame into a Bootstrap modal using jQuery when it is displayed

I am looking to include a YouTube embed in a modal only when the modal is visible on the screen using jQuery. Since I have multiple modals on the screen that affect page load time, I want to specifically load the video when that particular modal is visib ...

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

Error 404: Jquery Fancy Box Not Found

Help needed with JQuery FancyBox: I encountered a 404 error when trying to enlarge small images. Here is the code that I used: <a class="fancybox-buttons" data-fancybox-group="button" href="images/gallery/1_b.png" style="margin-right:100px;"><im ...

What steps should I take to create an in-site product filtering system with multiple dropdowns by utilizing a JSON file?

I have created an in-site redirect tool for our E-Commerce platform by utilizing resources from this website. I am looking to enhance the functionality of these in-site redirects by implementing a JSON file that contains options tailored to our existing li ...

Implementing an automated numbering system in Typescript to assign a unique id attribute to every object within an array

I am currently dealing with an array of objects: myArray = [ { "edoId": "4010", "storeName": "ABBEVILLE" }, { "edoId": "3650", "storeName": "AGEN" }, { ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

Help needed understanding the instructions from my teacher regarding the utilization of multidimensional arrays in C++

I am currently tackling a programming project for my course that involves creating a shape that can be manipulated using the mouse. I am utilizing eclipse on an oracle VM running Linux Mint. As part of the assignment, my professor provided some guidance in ...

What methods can I use to display or conceal certain content based on the user's location?

I'm looking to display specific content exclusively to local users. While there are APIs available for this purpose, I'm not sure how to implement them. I'm interested in creating a feature similar to Google Ads, where ads are tailored base ...

Limiting the amount of data that client-side apps can access is

When it comes to using angularjs, handling large amounts of data on the client side is quite easy. Is there a general guideline for how much data should be processed at once? I've been transferring files containing a few megabytes of text data and ha ...

What is the best method to access and raise a custom error across all components in Angular?

Incorporating a custom error into Angular is a task I am looking to achieve. My goal is to create a personalized error that can be easily thrown in any part of Angular, whether it be a service, controller, or elsewhere. I don't want to have to go thro ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...

What is the best way to designate my field as $dirty within my unique directive implementation?

I have created a custom dropdown/select directive to replace the default select boxes within my form. I also have some buttons that are set to disable while the form remains in its pristine state. app.directive('dropdown', function ($timeout) { ...

What methods are available to trigger an AutoHotkey script using JavaScript?

I'm in the process of creating a Chrome extension designed to streamline tasks. I've come to a stage where I require my extension to execute certain AutoHotkey scripts. Is there a method to execute an AutoHotkey script using JavaScript? (I' ...

Updating bump map in Three.js not working as expected

I have successfully loaded a model with the corresponding material file (.mtl) into my scene. I am now adding a bump map to it after loading: var mtlLoader = new THREE.MTLLoader(); mtlLoader.setPath('/models/'); mtlLoader ...

How can you pick specific elements from an array in JavaScript and place them into a new array?

Looking to choose a single element from one array out of multiple elements in another array. Here is the structure of the array: { "f": "Book2.csv", "v": 0, "vs": ["Year", "Month", "Customer_ID", "Collateral", "Exposure_amount"], "xs": ["C ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

What is the best way to modify an array within separate functions in a NodeJS environment?

I am facing an issue where I want to update an object inside the fetchAll() functions and then send it back after successful updation. However, the response I receive is '[]'. var ans = [] Country.fetchAll(newdate,(err, data) => { if ...

Updating individual items in the Redux state while displaying the previous version

I'm facing an issue with updating the reducer for my items (icdCode) in my array (icdCodes) within a React component. The update works only after reloading the entire component, which is not ideal. Initially, I had to deal with a duplicate key problem ...