Implementing functional programming techniques in JavaScript to populate n items

Trying to adopt a more functional programming style, I often run into the challenge of populating an array with n items.

Here is an example:

const items[];

for (let i = 0; i < n; i++) {
    items.push(new Item());
}

As far as I know, there are two side effects here: i is being mutated and so is items.

I am curious about the "pure" way to achieve this in JavaScript. I have experimented with methods like (new Array(n)).map(...) and (new Array(n)).forEach(...), but I am unsure of their advantages or disadvantages. Can anyone explain further, or direct me to a resource that delves into this topic?

Answer №1

This seems to be a great solution:

let num = 10;
const elements = Array.from(Array(num), val => new Element());

Learn more about the Array.from() method.


For an in-depth look at functional programming in JavaScript, take a look at this informative article.

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

Search for and swap out every item in a multi-tiered array

I am working with an array where the first column represents an id: var mainarray = [ ["1001","P6","P8"], ["1002","P7"], ["1003","P7","P8","P10"], ["1004","P6","P10"], ]; My goal is to replace each 'P' element with its corresponding animal from ...

If the handler of an event listener in jQuery requires a callback function, be sure to detach the event

Currently, I am facing a dilemma with a listener I have: $(document).on("keypress", function(e){ebClose(e,mpClose)}); I am exploring ways to dynamically delete this listener. The issue lies in the fact that I specifically want ebClose to receive mpClose ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

Display a PDF in a <div> when the menu is clicked

I have a project where I am trying to load a PDF in the middle of my page, inside a div, upon clicking on buttons in a side menu located on the left. While I have been successful in loading the PDF in the div, I am facing issues with triggering this action ...

Moving a div to a new spot

Looking to move a div - the expandable panel labeled 'Why Bother', to display at the bottom where it is currently seen. More specifically, I want it to be positioned at the top among the 8 panels in the HTML structure. (These panels are arranged ...

Problem with Jquery slider user interface

Encountering an issue with the min and max values of the jQuery Slider UI. Set the minimum value to 5000, maximum to 1000000, with step increments of 25000. However, when viewing it on the front-end, the displayed values are not as expected: https://i.sst ...

Update the withCredentials property to utilize the latest ES6 integrated HTTP request tool known as Fetch

What is the correct way to set withCredentials=true for a fetch promise return? fetch(url,{ method:'post', headers, withCredentials: true }); It seems like the MDN documentation covers everything about http-requesting, except for the u ...

The mtree script in external JavaScript is failing to function properly after dynamically inserting elements using jQuery

Here are the images showing a list of data that appears in all rows after the page loads. However, when I add a row using jQuery, the data does not show up. Please refer to image 2. Image 1 https://i.sstatic.net/xzn2c.png Image 2 https://i.sstatic.net/ ...

How can I implement Jquery to make my page scroll at a slower pace when a button is clicked?

I am a beginner when it comes to JQuery and I have been able to make my page scroll to the top and bottom but I would like to slow down the movement. How can I adjust the scroll speed? document.getElementById('sur2').onclick = function () { ...

Tips on inserting JS code into React component

I seem to be struggling with integrating my JS code into a React component. I attempted it, but unfortunately made a mess of things. Can anyone provide guidance on how to properly accomplish this? mycomponent.js import React from "react"; import Navbar ...

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

Incorporating elements dynamically using ajax and json can disrupt the overall design of the page

I have structured a page using jQuery Mobile. If I populate a list with static code: <script> document.write('<ul data-role="listview">'); document.write('<li data-icon="false"><a href="#" id="mortadella"><i ...

The execution of the Eval function results in an internal error

During my analysis of our application using the IE Edge browser, I noticed a peculiar behavior. When trying to execute the eval function, I encountered the following error message. I even attempted a sample like: eval("2"); Error: SCRIPT51: Internal ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Tips for updating the color of buttons after they have been selected, along with a question regarding input

I need help with a code that changes the color of selected buttons on each line. Each line should have only one selected button, and I also want to add an input button using AngularJS ng-click. I am using AngularJS for summarizing the buttons at the end ...

Creating Karma and Jasmine unit tests for an Angular service that relies on another module

I have gone through numerous articles but still cannot grasp the process of creating it. There is a particular module (“A”) that includes a service (“B”) which contains a specific function (“C”). This function uses another function (“E”) f ...

seamless blend of canvas distortion and gradual appearance of particles

Take a look at my work in progress on jsfiddle: https://jsfiddle.net/vzrandom/fkho6grf/8/ I'm experimenting with simplex-noise.js and dat.GUI to add movement to particles. Every 5 seconds, a simulated click occurs on the canvas triggering the start ...

Enabling sidebar functionality for every component in React JS using React Router v6

I am currently using react router dom v6 and encountering an issue where the sidebar disappears whenever I click on any component in the app. I need to find a way to keep the sidebar visible across all components. Sidebar Available https://i.sstatic.net/ ...

Ensuring the validity of a signed cookie in Node using Express

I'm currently working on incorporating signed cookies in Node's express module. I've reviewed the documentation, but I'm struggling to understand how to properly verify them. My understanding is that verification must occur on the serve ...

The error message received is: "EvalError: 'undefined' cannot be used as a function when trying to execute '_class.apply(this, arguments)'"

Every time I attempt to create instances of MyClass(), an error appears. s = new MyClass(); > TypeError: 'undefined' is not a function (evaluating '_class.apply(this, arguments)') This is the Class in question: class MyClass c ...