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

Using a personalized function in JQuery

I need to execute a JavaScript function I created after a JQuery event has been triggered. The function in question is called scrambleDot, and I defined it previously like so:var scrambleDot = new function() { //my code }. Here's the attempted implem ...

Dealing with Redis session management in the event of a database disconnection

Having trouble with losing connection to Redis, which is used for sessions in my Express App. var RedisStore = require('connect-redis')(express); sessionStore = new RedisStore(config.db.redis.connection); sessionStore.client.on('error' ...

Utilize React to process and submit payments through Stripe

I am currently working on integrating Stripe Elements with my React application. The JavaScript page below showcases the code I use to submit the payment form, which I have compiled from various sources online. Upon submitting the form, I receive a token; ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

JavaScript Code for Executing Function on Checkbox Checked/Unchecked

My goal is to display an image when the checkbox is checked and show text when it is unchecked. However, I am facing an issue where the text does not appear when I uncheck the checkbox. <input type="checkbox" id="checkword" onchang ...

Global Inertia Headers

How can I ensure that a custom header (Accept-Content-Language) is sent with every request, including Inertia manual visits? Below is the code snippet where I define and set the header: import axios from 'axios'; const lang = localStorage.getIt ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

Tips for implementing an element onClick change within a Redux container using React.js

After coming across a similar question by another user on this link, I found the answer quite clear. However, if you're dealing with a redux container, the states are transformed into props via the mapStateToProps function. So, my query is: how shoul ...

Requirements for generating random numbers in JavaScript. Can anyone help me understand how to implement this requirement effectively?

I've been experimenting with JavaScript to create a blackjack game, but I'm having trouble getting my code to work properly. My goal is for the getRandomCard() function to generate numbers between 1 and 13. Specifically, I want it to return 11 wh ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Bringing Together AngularJS and JQuery: Using $(document).ready(function()) in Harmony with Angular Controller

Can you lend me a hand in understanding this? I have an angular controller that is structured like so: angular.module('myApp', []) .controller('ListCtrl', function($scope, $timeout, $http){ // Making API calls for Health List ...

Fetching information with request query parameters in Node.js

Working on implementing email verification using nodemailer for user sign-ups. The process involves sending out an email containing a link (usually something like localhost:3000/verify/?id=##). After the user clicks the link, I can see that a GET request ...

Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this? ...

Update the innerHTML content dynamically every 5 seconds with Vue.js

I'm working on a new website and I'd like to spice things up by changing the header text with a random word every 5 seconds. Here's the starting point: const header = document.querySelector('.header') const needs = ['jacket& ...

Steps for setting up and shutting down the server during integration testing with Express and Supertest on NodeJS

One issue that continues to plague me is the "Address already in use::3000" error which pops up whenever I run my tests. This is what I currently have set up: package.json "scripts": { "test": "jest --watchAll --verbose --runInBand --maxWorkers=1" ...

Is it possible for Tinymce to provide me with precise HTML content that retains all styles (essentially giving me a true WYSIWYG

I find it puzzling how Tinymce is labeled as a WYSIWYG editor when what I see visually is not exactly what I get when I retrieve the HTML using getContent(). It seems more like "what you see is just what you see." Currently, when I use getContent() to get ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

Using AJAX to assign PHP session variables

Is there a way to update the SESSION variable named "fullname" on Page 2 without causing the page to refresh? This is my attempt using AJAX: HTML code for Page 1: <input type="text" name="fullname" id="fullname" placeholder="Full name"> <butto ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...