Contrasting splicing methods in JavaScript: Array() vs []

I'm currently attempting to implement JavaScript's version of Python's insert at index functionality.

var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]

const target = new Array(nums.length);

for (let i=0; i<index.length; i++) {
  target.splice(nums[i], 0, index[i]);
};

console.log(target);

The above code snippet results in:

[ 0, 4, 1, 3, 2, <5 empty items> ]

However, if I use the following code instead:

var index = [0,1,2,3,4]
var nums = [0,1,2,2,1]

const target = [] //new Array(nums.length);

for (let i=0; i<index.length; i++) {
  target.splice(nums[i], 0, index[i]);
};

console.log(target);

This time, it yields:

[ 0, 4, 1, 3, 2 ]

Why is there a difference between the two outputs? The second output is actually the desired one.

Answer №1

The function <strong>new Array(nums.length)</strong> creates an array filled with undefined values for the specified length.

If you declare <strong>const target = []</strong>, it will result in an empty array, denoted by [ ].

On the other hand, using <strong>const target = new Array(5)</strong> will create an array with five empty slots marked as [, , , , ].

Check out this link for more information on arrays in JavaScript.

Answer №2

When you create an array using this method:

const target = new Array(index.length);

The "target" array will be initialized with five empty slots. This can result in garbage values being stored, potentially impacting the data after insertion.

However, if you initialize the array like this:

const target = [];

The "target" array is created without specifying a size limit. This means you can insert any number of dynamic values into it.
('n' represents the size of the array)

It's recommended to always use the second option as it's considered a best practice for working with JavaScript arrays.

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

Looking for a demonstration using dust.js or handlebars.js in a two-page format with express3.x and node?

Currently, I am in the process of selecting a templating engine to use. While I have come across numerous single-page examples utilizing template engines, I am specifically searching for a practical example that demonstrates handling two distinct pages whi ...

What is the best way to obtain repetitive models for a particular brand in this scenario?

I am looking to display a specific subset of Chevrolet models in my code. Here is the snippet: <body ng-controller="marcasController"> <ul ng-repeat="marca in marcas"> <li ng-repeat="tipo in marca.modelo">{{tipo.nombre}}</li> ...

Auto-populate AngularJS form using PHP array via JSON and $http

I came across a fantastic autocomplete feature in this plunker that I need to replicate using a PHP array with $http. When I tried adding an alert to check my array, it worked perfectly. However, I'm stuck on how to implement the filter in AngularJS. ...

Fulfill the promise once the callback has been triggered

In my code, I am working on preventing the method _saveAddress from being executed multiple times. To achieve this, I have created a promise for the method. const [pressEventDisabled, setPressEventDisabled] = useState(false); <TouchableOpacity style={s ...

Discover the ID or HREF linked to the current date using moment.js

I'm looking to dynamically add an active class to the current day in my web application. An example of how it currently works is shown below: $( document ).ready(function() { $('a[href*="2208"]').addClass('active'); }); My goal ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Extracting information from JSON in Swift

Need some assistance with this The JSON URL data I parsed looks like this: { AREA = ( { "area_name" = "Bhaktamadhu Nagar"; "city_id" = 4; id = 31; price = "100.00"; }, ...

Experience a unique full-screen video background on page load with this innovative JavaScript feature! Visit the included JS

Looking to enhance my website by displaying a random fullscreen background video selected from a folder of videos that I will manage. The goal is to steadily increase the number of videos in the folder (e.g., bg1.mp4, bg2.mp4, etc...) and have the code aut ...

Ways to invoke the parent function from a child component in JavaScript

Is there a way to execute a parent function within the Child class while preserving the current context (this) of the Child? I attempted using Parent.testFunc.call(this);, but it resulted in an error (Cannot read property 'call' of undefined). ...

Execute Neo4j commands using Cypher scripts within JavaScript

Currently, I am utilizing the official Neo4j Javascript driver to establish a connection with my database. My goal is to execute queries directly from .cypher files, as I find that writing them as strings leads to more errors. I would prefer not to read t ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...

Retrieve a specific item from the JSON dataset

Currently, I am in the process of working on my own project using jQuery, AJAX, and JSON. My goal is to retrieve data from the TMDB API by allowing users to search for a specific term, such as the movie "Fight Club." The desired outcome is to display a mov ...

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

Can a virtual host proxy utilize an external IP address?

Currently, I have three node apps running on the same server but with different localhost ports. My goal is to create a router that acts as a proxy for each app and then place this proxy in a virtual host. While I am currently testing this setup on my loca ...

What is the best way to create 2 select boxes that will disable each other if they match, and then automatically choose the second option so they do not match

Is there a way to have 2 select boxes automatically change one option to the second option on one box when they match? Instead of using an "alert", I am looking for a function that can automatically update one option in one of the select boxes if they mat ...

Retrieving data from nested JSON by leveraging distinct fields with AngularJS

Here is a sample json data: { "id":14, "discussion":8, "parent":0, "userid":2, "subject":"communication skill discussion 2", "message":"<p>hi all to communication discussion 2 </p>", "children":[ 24, 16, ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

Using bootstrap with a navbar in an asp.net mvc application proves to be challenging

There are only a few bootstraps that work with this site, such as the default and lumen bootstrap. You can find them on However, other bootstraps like materia and flatly seem to be causing display issues. Here's an example of how it looks: Edit: Bel ...

Ways to eliminate shared elements in PHP arrays

Creating a new array by merging and removing duplicates $arr1 = [3,4,5,6]; $arr2 = [5,6,7,8] $arr3 = array_merge(array_unique($arr1), array_diff($arr2, $arr1)); print_r($arr3); ...

Lack of Synchronization in JavaScript Dates

When receiving a time value from the client in epoch format (milliseconds since Jan 1 1970) on my node server, I convert it using the Date() object and display it as follows: var d = new Date(epochTime); var year = d.getFullYear(); var mo = d.getMonth(); ...