Initializng an array with null values in Javascript

Can you explain why this Javascript code:

var myArray = new Array(3);
    

does not produce the same result as:

var otherArray = [null, null, null];
    

? Keep in mind that (myArray == otherArray) returns false.

Additionally, is there a way to create an array like otherArray, which contains 'nulls' but with a custom size?

Note:

[undefined, undefined, undefined] 
    

is also found to be unequal to myArray.

Answer №1

Utilizing EcmaScript 6 (ES2105), constructing an array with five null values can be accomplished effortlessly:

const newArray = new Array(5).fill(null);

MDN Reference Link

Answer №2

When you initialize an array like var myArray = new Array(3);, it creates an empty array. Therefore, even if myArray and otherArray had the same values - three undefined values - they would still be considered different arrays. This is because an array is treated as an object, and a variable like myArray merely holds a reference to that object. Having two objects with identical values does not make them equal.

For example,

var x = new Object();
var y = new Object();
console.log(x===y); // Outputs false.

Additionally:

var person1 = { name: "John" };
var person2 = { name: "John" };
console.log(person1===person2); // Outputs false.

Note:

Also, in the case of initializing an array using var myArray = new Array(3), the indices are not initialized, as noted by Paul in the comments.

For instance, if you do this:

var nums = [1,2,3];
console.log(Object.keys(nums));

You will see:

["1","2","3"];

However, if you try:

var nums = new Array(3);
console.log(Object.keys(nums));

You will get an output of:

[]

Answer №3

One key thing to remember is that when comparing two Arrays or any other Object, you must either iterate through them or serialize them because comparing their references will always result in false


Is there a way to create an array like otherArray, which contains only 'null' values but with a custom size?

Here is an alternative approach for generating Arrays with a default value for each item and all indices set:

function generateArray(length, item) {
    var array1 = [item],
        array2 = [];
    while (length > 0) {
        if (length & 1) array2 = array2.concat(array1);
        array1 = array1.concat(array1);
        length >>= 1;
    }
    return array2;
}

Now,

generateArray(7, null);
// [null, null, null, null, null, null, null]

Answer №4

Upon conducting some investigation, I discovered that using Array(length).fill(null) is not the most optimal solution in terms of performance.

The solution with the best performance was:

const nullArr = Array(length)
for (let i = 0; i < length; i++) {
  nullArr[i] = null
}

Take a look at this:

const Benchmark = require('benchmark')
const suite = new Benchmark.Suite

const length = 10000

suite
  .add('Array#fill', function () {
    Array(length).fill(null)
  })
  .add('Array#for', function () {
    const nullArr = Array(length)
    for (let i = 0; i < length; i++) {
      nullArr[i] = null
    }
  })

  .on('cycle', function (event) {
    console.log(String(event.target))
  })
  .on('complete', function () {
    console.log('Fastest result: ' + this.filter('fastest').map('name'))
  })

  .run({ async: true })

The performance results are as follows:

Array#fill x 44,545 ops/sec ±0.43% (91 runs sampled)
Array#for x 78,789 ops/sec ±0.35% (94 runs sampled)
The fastest option is Array#for

Answer №5

Try using [...new Array(76)] to create an array with 76 undefined values.

console.log(
  [...new Array(76)]
)  

Another option is to fill the array with null.

console.log(
  [...new Array(76).fill(null)]
)  

Answer №6

Success! I found a solution.

let list = [Array(9).fill(null)] 

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

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...

The performance of the bubble sorting program is not up to par

I am currently working on creating a bubble sort program in C# to sort random integers stored in an array. I need to implement this for arrays of various lengths such as 100, 1,000, 10,000, and so on. While I have some code that compiles correctly, it is n ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...

Issue with idangero.us swiper: resizing problem occurs when image exceeds window size

Having an issue where resizing my window causes the image to become larger than anticipated. As a result, the current image is partially cropped on the left side while the previous image starts to show through. Here's a description of what's happ ...

Exploring click event beyond React Component: Jest + Enzyme Testing

I am looking to create a Jest and Enzyme test for a component that includes an event listener. The purpose of the test is to ensure that when a mousedown event occurs outside of a specific HTML element, a change is triggered (for example, toggling a state ...

Once invoked by an ajax request, the $().ready function is executed

The functionality of this code is flawless when running on its own. However, once I make an ajax call to it, the code fails to execute. I suspect that the issue lies within $().ready, but I haven't yet identified a suitable replacement. Any suggestio ...

Is it possible to retrieve all data from the Google translation API?

In my React app, the main component contains this function: componentDidMount(){ const land = ["Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Assamese", "Aymara", &qu ...

Exploring the Dynamic Resizing of Geometry Meshes in three.js

Is there a way to adjust the height of my geometry meshes dynamically? You can check out my demo here. ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Target specifically the onhover div element using JQuery and trigger the smooth sliding down effect with the SlideDown() function

Is it possible to create a unique JQuery slidedown() function that will only be applied to the div where the mouse is hovering? I have managed to make it work by giving each div a separate class, but when I name them all the same, it triggers the slide do ...

What is the correct way to utilize preloads and window.api calls in Electron?

I am struggling with implementing a render.js file to handle "api" calls from the JavaScript of the rendered HTML page. The new BrowserWindow function in main.js includes: webPreferences: { nodeIntegration: false, // default value after Electr ...

The has-error class cannot be applied to certain input elements

I am currently in the process of validating some inputs within a modal: <div id="modal-section" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="m ...

What is the reason for me encountering an error message stating "Access-Control-Allow-Origin" does not allow this origin?

I encountered the following issue: Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin when using the code snippet below: var http = new getXMLHttpRequestObject(); var url = "http://gdata.youtube.com/action/GetUploadToken"; var se ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

Invoke multiple stored functions using JavaScript, beginning with this one

One way to store and call a function later is by assigning it to a variable, like so: var storedFunction = functionName; //Later On storedFunction(); //Equivalent to functionName() If you want to store a function and also execute 'this' when ca ...

Prevent horizontal HTML scrolling while displaying a layer

I am currently working with a .layer div element that darkens the page to highlight a modal. However, I have encountered an issue where upon triggering the event, the div does not occupy 100% of the screen and the original browser scroll bar disappears. I ...

The dirtyVertices feature in Three.js seems to be malfunctioning

In my three.js project, I created a 12*12 plane and attempted to modify its vertices between two renderings without success. Despite adding the following code, no changes were observed: ground.geometry.dynamic = true; ground.geometry.__dirtyVertices = tr ...

Why is my Feed2JS RSS feed functional locally but not operational after deployment on GitHub Pages?

I've been using feedtojs.org to display my Medium blog posts on my GitHub Pages website. Strangely enough, it works perfectly fine on my local server but not on the actual domain. The RSS feed is valid. Here's how it appears on my local server: ...

Updates to Boolean Arrays in Ruby

Struggling with this code challenge - I'm required to loop through an array of booleans 100 times. Here are the instructions: Cats in Hats You've got 100 cats. The rules are simple: each time you visit a cat, you need to change its hat status ( ...