Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console:

var object = {0:0, 1:1}

I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redefine the object as:

var object = {"0":0, "1":1}

It turns out that all four calls work without any issues. However, things take an unexpected turn when I redefine the object like this:

var object = {a:0, 1:1}

Now, when I try to call object[a], a ReferenceError is thrown stating "a is not defined". Strangely, using object["a"] returns 0 even though the property name in the declaration is not a string. It seems like JavaScript assumes I am referencing a non-existent variable in the first example. But why do both object[0] and object["0"] yield proper results? Could it be that JavaScript automatically converts numbers since they can't represent variable names? What are the underlying rules governing this behavior, and does it apply universally or only within object bracket notation?

Answer №1

By utilizing brackets, the content contained within them is assessed. What do you suppose the result of the following expression will be?

 a

Confused? If "a" hasn't been defined as a variable, it doesn't hold any meaning. When you employ the . notation, the term that comes after this symbol (which must strictly be an identifier) is viewed as a string. This is simply how the language functions.

Answer №2

If you're facing a ReferenceError when attempting to access object[a], it's likely due to the fact that a is being treated as a variable in JavaScript rather than a string value containing the letter 'a'.

To resolve this issue, consider using the dot notation like object.a or the bracket notation with object["a"]

object.a;    //=> 0
object["a"]; //=> 0

object[1];   //=> 1
object["1"]; //=> 1

Alternatively, you can utilize a variable for accessing the object properties

var x = "a";
object[x];   //=> 0

var y = 1;
object[y];   //=> 1

Answer №3

Indeed, you are correct.

a serves as a token that the engine interprets as a variable.

If you input "a", JavaScript recognizes it as a string-primitive.
If you input 0, JavaScript recognizes it as a number-primitive.

Aside from utilizing obj.a, obj["a"], obj[0], obj["0"], you can also do:

var a = 0;
obj[a]; // 0

Your application is encountering issues because a has not been defined yet, and you're trying to use it now.

This behavior is expected.
The content within the brackets isn't considered a "part" of the object -- it's a method of requesting "provide me with the value of the object associated with this key", where the key may be a number or string (or something that can be coerced into a string or number).

In the future, via maps and weakmaps, you will be able to utilize other objects/functions as keys too.

var obj  = new Map(),
    func = function () { },
    el   = document.getElementById("myId");

obj[func] = 1;
obj[el]   = 2;

Currently, these functionalities technically function... ...however, solely due to them being converted to their respective string values... ...thus, if you had two functions that were identical (but essentially distinct objects), they would overwrite values at present.
Within a map, they would be treated as separate entities.

Presently, working with DOM elements poses even more challenges, especially when there's a need to store numerous elements and associate references to them without constant re-lookups... ...yet for now, one must assign a unique ID number/key to each one, store that, recall the keys, and then establish a subsidiary object to retain the desired information...

However, in the near future, with maps, one could accomplish the following:

var my_els = document.querySelector(".lots-of-els");

for (let el of my_els /* also the future */) {
    console.log( my_map_of_data[el].info );
}

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

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

Do I have to divide the small functions in my Node.js controller into smaller ones?

When signing up users in my controller, do I need to break up the sign-up steps into individual asynchronous calls or is one big asynchronous call sufficient? Each step relies on the previous one: Validate user Create user Create group Add user to group ...

I made a mistake with my git repository. Should I try to fix it or just start fresh?

After spending months learning web development, I recently completed my first project. Unfortunately, right before deployment, I made a mistake with my backend git tree. I attempted to resolve the issue using suggestions from other resources, but none of ...

What is the best way to determine the dimensions of a KonvaJs Stage in order to correctly pass them as the height/width parameters for the toImage function

Currently, I am using KonvaJs version 3.2.4 to work with the toImage function of the Stage Class. It seems that by default, toImage() only captures an image of the visible stage area. This is why there is a need to provide starting coordinates, height, and ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

The JavaScript audio is not working for the first three clicks, but starts playing smoothly from the fourth click onwards. What could be causing this issue?

$(".btn").click(function(event){ playSound(event.target.id); }); function playSound(name){ $("." + name).click(function() { new Audio("sounds/" + name + ".mp3").play(); ...

Event fails to trigger when attached to different elements

Currently, I have an onchange event linked to the input text box and an onclick event attached to a text link. Interestingly, when I click on the link after editing the textbox, the click event does not trigger - instead, the change event is fired. If you ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

Is the detailedDescription missing from the JSON-LD schema crawl?

I am currently utilizing the Google Knowledge Graph Search (kgsearch) API to retrieve Schemas from schema.org. However, I am encountering an issue where some nested elements are not being recognized as JSON or I may be overlooking something... url = "http ...

Enhance the functionality of the kendo grid by incorporating additional buttons or links that appear when the

Is there a method to incorporate links or buttons when hovering over a row in a kendo grid? I've searched through the documentation and looked online, but haven't found a solution. I'm considering if I should modify my row template to displa ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Verify JSON data from server using AngularJS

My understanding is that in Angular, the HTTP service has two checks for 'success' and 'error' when connecting to a service. I have already handled these checks as my first step. The issue I am facing now is with the data in my JSON fi ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

The issue of receiving an undefined JSON response persists in an AJAX file upload scenario

Currently, I am utilizing Valum's Ajax File uploader for handling same-page file uploads. The issue I'm facing is that despite numerous attempts and variations in my script, I consistently receive "undefined" when trying to access responseJSON[&a ...

Excessive form inputs extend beyond the modal when utilizing Bootstrap 3

Having an issue loading a modal with Angular and populating it with a template. The main problem I'm facing is that the inputs are extending beyond the boundaries of the modal - attached below is a screenshot illustrating the problem: Below is the c ...

What is the best location in Backbone.js to store code unrelated to the view, such as ads and analytics?

In my development of a backbone.js application, I have come to understand the role of each backbone "class" as follows: Model: This represents the data object, where the outcome of an API call is stored. Collection: An organized group of models, for exam ...

What is the best way to send additional data with getServerSideProps() in Next.js?

Not sure if this is a silly question, but I am currently working with a Django API and attempting to implement pagination on the search page using Next.js. As a newbie to Next.js, I have scoured the web for a solution but haven't found anything helpfu ...

What is the best way to remove a specific HTML section using a JavaScript function?

I am struggling to figure out how to remove a specific HTML section using a button that is contained within the section itself. The section I want to delete was initially added by clicking a different button. Although I can successfully add a new section ...