What is the reason that a JavaScript array element, when created using dot notation, exists but is not included in the array's length

Surprisingly, you can actually use dot notation to create a "property" in a JavaScript array:

const arr = [];

arr.dot = "notation";

console.log(arr.dot); // "notation"

It's strange, but it works. However, even with the added property, the array's length remains 0:

const arr = [];

arr.dot = "notation";

console.log(arr.dot); // "notation"

console.log(arr.length); // 0

This raises two important questions:

  1. Why does assigning a property using dot notation not affect the array's length?
  2. How is it possible to assign a property to an array using dot notation?

Answer №1

When working with JavaScript, it's important to remember that an array is essentially just another type of object. In this case, you are adding the property dot to the object.

You can verify that an array is indeed an object by using:

typeof arr.

The value of the length property is determined by the number of numeric entries contained within the array.

For more detailed information, refer to the following excerpt from developer.mozilla.org:

Arrays do not allow the use of strings as element indexes (similar to associative arrays); instead, integers must be used. When setting or accessing values using bracket notation (or dot notation) with non-integers, the action does not affect the actual array elements but rather interacts with a variable associated with the array object's properties collection. It's crucial to understand that these named properties are distinct from the list of array elements, which means traditional array operations cannot be performed on them.

Answer №2

The dot notation in this case is actually assigning a property to the array instead of pushing a new value into it.

const myArray = ['apples', 'bananas'];
console.log(myArray);
myArray[2] = 'peach';
console.log(myArray);

You might be drawn towards objects because of this behavior, where properties can be easily assigned:

const myObject = {
  id: 1,
  name: 'Pig',
  type: 'animal',
}

// Standard dot-notation assignment
myObject.sound = 'Oink!';
console.log(myObject);
// "Computed" assignment
myObject['emoji'] = '🐷';
console.log(myObject);

For further insight on this topic, check out this resource.

But why can't you do something like this with arrays:

const myArray = ['choclate', 'strawberry'];
myArray.pinapple = 'Tasty';

Arrays function more as lists, so adding attributes like a "describer" doesn't align with their purpose.

While setting properties for an Array is possible (as they are based on JavaScript objects), it's not typically used in the way you may think.

Here's when I might employ the "dot notation" assignment for an Array:

let zoo = ['Dolphin', 'Lion', 'Monkey'];
console.log(zoo);
// Built-in property
console.log('I have', zoo.length, 'animals in my zoo!');
// Adding a property "income"
zoo.income = 500;
console.log('My zoo has £%s', zoo.income);
// Operating on income property
zoo.income += 50;
console.log('My zoo has £%s', zoo.income);
// Implementing a method for closing down the zoo
zoo.closeDown = () => {
  zoo = [];
  zoo.income = 0;
  return true;
}
zoo.closeDown();
console.log(zoo);
console.log('My zoo has £%s', zoo.income);

In some scenarios, it might make sense to maintain animals in a zoo as an array and build up methods and properties from there, rather than using an object.

If you're interested in retrieving a list of these properties/methods, you can do so like this:

const myArray = ['Foo', 'Bar'];
myArray.isCool = true;
console.log(myArray);
console.log(myArray.length);
let i;
for (i in myArray) {
  console.log(i, myArray[i]);
}

By using the for (i in ...) syntax, we iterate through the array's properties as if it were an object since arrays extend the Object class to some extent.

Learn more at this link.

Answer №3

  1. size specifically measures the numerical attributes.
  2. Arrays, being objects, allow for additional properties to be attached.

There's no need to solely rely on dot notation; you can also do

array["period"] = "syntax";

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

Is there a way to use moment js to change the date format to just show the month and year?

Want to transform the date time format using momentjs 2017-02-01T00:00:00.000Z into 02-2017 ( month-year ) Looking for a way to change the date format to display only month-year using momentjs? I attempted it like this: var MnthYr = moment(2017-02-01 ...

Sharing variables across multiple PHP files using $GLOBALS

I am working with a file named index.php, which generates a link to a page that I only want my user to access if a certain condition is met ($var == True). To achieve this, I aim to utilize the $GLOBALS array instead of the $_SESSION array since the latte ...

React Navigation Item Toolbar Misplacement

I've been trying to align the navigation item with the logo on the same line within the toolbar, but I'm facing an issue where they keep appearing in different rows. To see the error for yourself, check out the code sandbox here. This is how I s ...

I am unable to locate the appropriate TypeScript type for the `displayName` attribute when it is used as a prop for the `type` component

Having trouble finding the correct type as mentioned in the title. After inspecting with DevTools, I have confirmed that every component I am programmatically looking at has Component.type.displayName. For anything that is not an ElementType, the type is a ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Modify the JSON structure of a deeply nested object

I am attempting to convert a deeply nested JSON object from one structure to another so that it can be properly used with the jQuery Nestable library. Here is the original format I am working with: { "scanned": { "a3": { ...

The flow of browsing the web and executing scripts in a web browser

I'm really struggling to grasp the logic behind this function I'm working on. public void PortalLogin(AutoResetEvent signal) { // Navigate to portal string portalUrl = "website_name"; ...

Tracing a path with a snapping motion using my thumb

Before we begin, let's take a look at the example below. The functionality of this component should mimic that of an input type range. However, I am facing some challenges in calculating the step value and snapping the thumb onto the trail based on t ...

JavaScript: Splitting strings with multiple delimiters

Can I use a Java Script function to divide a string into multiple parts? var string = "This is a test text, again, this is a testing text"; For instance, I can split the string using , like this: string.split(','); resulting in: var string = [ ...

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...

How can I retrieve the input value on the current page using PHP?

Hey there, so I'm pretty new to PHP and I have a question. Is it possible to retrieve the input value from an existing input field on a page using PHP when the page loads, and then assign that value to a variable? For instance, let's say I have ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Deleting the previous ion-view from DOM in Ionic v1 with Angular

I have been working on modifying an app built in Ionic v1. Within the app, there is a primary View titled 'Client's Profile' that contains links to two other Views: Support Request and Complaints. In the Support Request view, there is a Te ...

How to choose multiple checkboxes in AngularJS by utilizing the shift key and mouse click feature?

Is it feasible to utilize shift and mouse click for selecting multiple elements on a table using AngularJS? In my table, the first column consists of checkboxes and I am interested in employing the SHIFT key along with mouse clicks to select several rows ...

Encountering an unexpected token error - Karma and Webpack testing having trouble with the forward slash symbol

I have been facing some issues while setting up my angular tests. The error message I keep getting is: PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR SyntaxError: Unexpected token '/' at app/components/dropdown/dropdown.spec.ts:1 PhantomJS 2.1.1 ( ...

Confusion arises when assigning an array to a pointer

While going through a C tutorial, I came across a line of code that left me feeling confused. Here is the snippet in question: int main(int argc, char *argv[]){ ... char **inputs = argv+1; // This line is a bit puzzling ... return 0; } I&apos ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

Merging and Reorganizing files using Gulp based on Folder names

In my gulpfile.js, I am attempting to configure a setup that concatenates all .js files located in the src/js folder and names them based on their parent folder. Here is an example of the folder structure: project | +-assets | | | +-app.min.js | | | +-ve ...

Using Vuejs to dynamically render raw HTML links as <router-link> elements

Hey there, I'm just getting started with VueJS and I've been doing some interesting experiments. I created a backend service using Python/Flask that provides me with a string of HTML code containing many tags. My goal is to render this HTML insid ...

Appending a JSON object to an array does not result in the object being added to the

Can anyone help me with an issue I'm facing? I have a code snippet where I am trying to push a JSON Object into an array, but the array is not updating properly. It only shows the last pushed element. var myData = {}; var id = 0; $("a").on('cli ...