An Empty Set Produced a Size of 5

Recently, I began delving into the Rapid JavaScript Training course by Mark Zamoyta on PluralSight and encountered a fascinating concept. Through two examples, he demonstrated an intriguing concept that I've been attempting to comprehend.

I'm puzzled about how the length of entries is captured after creating an array using the new Array() method, especially since it resulted in an empty array []. In theory, shouldn't it return -1 since it's empty like this []?

  var entries = [1,2,3,4,5];
  entries.length
  => 5
  entries
  => [ 1, 2, 3, 4, 5 ]

  var entries = new Array(5);
  entries.length
  => 5
  entries
  => []

Answer №1

let myArray = new Array(5);

If you create an array by specifying the size in the constructor as shown above, memory space will be reserved for 5 elements in the array. Upon inspection, the array would look like this:

console.log(myArray[1]);
=> undefined
console.log(myArray.toString);
=> ,,,,

It's evident that the array has five slots, each containing the value of undefined. Therefore, the array isn't truly empty.

Initialising an array in this manner may not be considered best practice, as there is limited utility in doing so. If you attempt to add elements using push, the result will be as follows:

myArray.push("value");
console.log(myArray.toString);
=> ,,,,,value

This outcome is likely not desired. It is recommended to initialise arrays without specifying a size to avoid such situations:

let myArray = [];

Answer №2

The size of an array in JavaScript is not dynamically calculated using the length property. Instead, it can be manually set through the constructor or by an assignment, and it adjusts as elements are added or removed (Reference):

Whenever a property with an array index as its name is added, the length property is updated to be one more than the numeric value of that index if necessary.

This property is constantly updated and not calculated. For example, using the constructor new Array(5) will initialize an array with a length of 5. You can also manually set the length, which will either fill in with undefined or truncate the array accordingly:

var myArray = [];
myArray.length = 3;
// myArray is now [undefined, undefined, undefined]

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

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

Error encountered while parsing JSON data from LocalStorage

Storing an object in localStorage can sometimes lead to unexpected errors. Take this example: function onExit(){ localStorage.setItem("my_object","'" + JSON.stringify(object) + "'"); } When retrieving this data from localStorage, it may loo ...

SyntaxError: An invalid character was encountered (at file env.js, line 1, column 1)

This marks my debut question so kindly indulge me for a moment. I recently stumbled upon a guide that outlines how to dynamically alter environment variables in a React project without the need for re-building. You can find the guide here. The method work ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Generate an image of a "button" with dynamic hover text

I am trying to create a clickable image with dynamically changing text overlaid on it. I have the PHP code that retrieves the necessary information for the text, but I am struggling to create the button as I am new to this type of task. Here is an example ...

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Utilize Javascript to pull information from a REST API and generate a dynamic table with the retrieved

Generating a table from JSON data obtained from a REST API without utilizing Angular poses a challenge in a specific application. My query is: Is it necessary to use var table = document.createElement("TABLE"); within the script to construct the entire ta ...

What is the proper way to utilize JQuery and Ajax to communicate with a global function in writing?

My goal is to retrieve data from an AJAX request and store it in a global variable. Despite trying to make the call synchronous, I am encountering issues where the value of the global variable becomes undefined outside of the Ajax request. I have attempt ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: https://i.sstatic.net/iBSof.png I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { ...

What is the best way to effectively clear memory in THREE.js?

After successfully rendering the model, rotating and zooming work perfectly. However, when attempting to clear the scene by clicking the button#clear, issues arise. The expectation is to traverse through the scene, add its children to an array, iterate ov ...

Clear Vuex state upon page refresh

In my mutation, I am updating the state as follows: try { const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, { headers: { Accept: 'application/json', 'C ...

Unravel a Base64 encoded string with the power of CryptoJS

I am in the process of developing a basic webpage where the objective is to send an encrypted message to the server, which will then create a file with that content. Subsequently, a link is generated for the recipient to access the encrypted value by provi ...

Matching exact multiple words with special characters using Javascript Regular Expression

My issue involves using RegExp to match multiple words with dynamic values. Whenever a special character like "(" is included, it interprets it as an expression and throws an Uncaught SyntaxError: Invalid regular expression error. let text = 'worki ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

Experiencing issues with applying bootstrap style to pagination when using react-js-pagination

I am currently utilizing the react-js-pagination library to showcase page numbers within my application. Bootstrap has been included in the public/index.html file and can be accessed using className in other components. When it comes to the Pagination com ...

Error: Identifier Not Expected (Exploring Generators in ES6)

After delving into the information provided in the generators documentation on MDN, I devised a straightforward experiment: var nodes = { type: 'root', value: [ { type: 'char', value: 'a' }, { type: &ap ...

Using jQuery to save PHP form output into an Excel spreadsheet

I have a PHP-enabled form on my website for collecting Address details. Currently, the output is sent to my email inbox. However, I would like the output data to be saved in an external Excel file named "address.xls" using jQuery/JSON. The input fields of ...