Isn't the ES6 spread operator responsible for flattening arrays?

I have a general question that isn't specific to React, so I hope it's okay to ask here. I always believed that the spread operator flattens an array. However, in the following sum function that sums the arguments, we can use .apply to pass in the values:

function sum() {
    return arguments.reduce((total, number) => total + number, 0);
}

var values = [2, 4, 8, 12, 16];

console.log(sum.apply(null, values));

I initially thought that we could simply add the spread operator to the function and use it to flatten the array, enabling us to use call. (I understand that call wouldn't be necessary in this case, but I was surprised because I thought the spread operator flattened the array:

function sum() {
    return [...arguments].reduce((total, number) => total + number, 0);
}

var values = [2, 4, 8, 12, 16];

console.log(sum.call(null, values));

However, this returns the string 02,4,8,12,16

Answer №1

The reason for this occurrence is due to the fact that the arguments object behaves like an array. This array is then converted to a string.

According to the call documentation,

While the syntax of this function is very similar to that of apply(), the key distinction is that call() takes a list of arguments, whereas apply() takes a single array of arguments.

The following methods should yield the expected results:

sum(...values);
sum.call(null, ...values);
sum.apply(null, values);

It is worth mentioning that arguments and call are not preferred in ES6.

Answer №2

The arguments object behaves like an array structure, so when passing it as an argument, it is similar to a nested array. Utilizing the spread operator converts it into an array format like [[2, 4, 8, 12, 16]] (i.e., [...[[2, 4, 8, 12, 16]]]). Using the reduce method applies 0 + [2, 4, 8, 12, 16], resulting in "02,4,8,12,16".

To make it functional, you can pass the array values as arguments using Function#apply or retrieve the first argument.

function sum() {
  return [...arguments].reduce((total, number) => total + number, 0);
}

var values = [2, 4, 8, 12, 16];

console.log(sum.apply(null, values));

function sum() {
  return [...arguments][0].reduce((total, number) => total + number, 0);
}

var values = [2, 4, 8, 12, 16];

console.log(sum.call(null, values));

For more information: Understanding the difference between call and apply

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

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Does the Width Toggle Animation fail to function in FireFox when using jQuery?

Has anyone else encountered this issue with the jQuery animate function not working in Firefox but working fine in IE8, Opera, and Chrome? I'm experiencing this problem and wondering if there's a workaround to make it work in Firefox as well. ht ...

Seeking materials for WebDriverJs?

It has come to my attention that there are some valuable resources available: http://docs.seleniumhq.org/docs/03_webdriver.jsp https://code.google.com/p/selenium/wiki/WebDriverJs However, I am curious if there exists a comprehensive website that prese ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

JS Metro app is not receiving push notifications

Currently, I am in the process of integrating push notifications into a JS Metro app. After registering for push notifications and obtaining a Channel URI, I update it in my locally hosted WCF service if it is new. Within my service, I authenticate with WN ...

The element within the array object is not properly defined and is causing error messages to be displayed

Whenever I try to use Icons[link.label] in my const, I receive the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'iconsProps'. No index sig ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

Which specific indexOf method is the most appropriate for my use case?

While exploring a codebase, I came across this code snippet that adds the indexOf function: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments ...

If the browser is IE8, utilize jQuery to open a custom HTML page

I am looking to detect and control browser compatibility. I attempted the following method and it was successful: <!--[if IE 8]> <script type="text/javascript> alert('hey'); </script> <![endif]--> However, I ...

The object does not contain a 'navigation' property within the 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' type

As a beginner in react native, I am facing some challenges with the components I have created. Let me share them: List of Playlists: export default class Playlists extends Component { playlists = [ ... ]; render() { const {navigation} = th ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

When attempting to redirect to a different page using setTimeout, the loading process appears to continue indefinitely

Currently, I am utilizing the following script: setTimeout(function(){ window.location.href = '/MyPage'; }, 5000); While this script successfully redirects me to /MyPage, it continuously reloads every 5 seconds. Is there a way to r ...

Is there a straightforward method for tallying numbers in mongoose?

Here's the code I've written: Company.count({}, function(err, company) { Checkpoint.count({}, function(err, checkpoint) { Guard.count({}, function(err, guard) { Device.count({}, function(er ...

Manipulating images separately using the canvas

Currently, I am utilizing an HTML5 canvas to generate a collection of trees alongside their corresponding shadows. My objective is to ensure that each shadow corresponds with the position of a designated light source. While I have successfully drawn each t ...

Error in onchange event due to incorrect index variable

My goal is to add onchange events to select tags within a div that contains multiple tags. To achieve this, I am using a for loop to attach events to each tag. The purpose of these events is to update a select tag in another container by removing the "disa ...

Endless Google Locations Instances

My database entries are being displayed in a table using input fields. I want the Location field for each entry to be automatically completed using Google's API. HTML: <input name="edit_airplane[1][location]" type="text" class="airplane_location" ...

The Vuejs single-file component fails to display on the page

Even though there are no errors in the browser and Webpack compiles successfully, the message "hello from dashboard" is not displaying on the page. I am currently using Vue version 2.6 In my main.js file: import Vue from 'vue' Vue.component(&a ...

What is the best way to fill out a mandatory text field within the text area?

I am currently facing a challenge with making the comment field mandatory in my PHP application. Despite my lack of expertise, I have been unsuccessful in finding a solution so far. Below is an example code snippet where PHP generates the comment field. Du ...

Creating a four-dimensional array in PHP can be achieved by nesting multiple arrays within each

When I run a distinct query, I end up with a lot of data. Take a look at this picture of a busy cat: My goal is to group the final status by nodeid, portid, and total, which represents the total status. I need to create an array that looks like this: [ ...

The functionality to apply a color class to a navbar item when clicked is malfunctioning

I'm attempting to create a navigation bar using text that toggles the visibility of different divs. I want the selected option to appear in red, indicating it has been chosen, while deselecting any other options. I am new to JavaScript and thought add ...