What is the reason for the success of bracket notation in this case while the dot notation fails to

var albumInfo = {
  2548: {
    title: 'Slippery When Wet',
    singer: 'Bon Jovi',
    songs: ['Let It Rock', 'You Give Love a Bad Name']
  },
  2468: {
    title: '1999',
    singer: 'Prince',
    songs: ['1999', 'Little Red Corvette']
  }
};

console.log(albumInfo[2548])

Encountering an issue with this line of code:

console.log(albumInfo.2548)

Answer №1

MDN has an informative page dedicated to Working with objects where the emphasis is on proper usage of property names:

An object property in JavaScript must adhere to certain rules, such as being a valid identifier without spaces or hyphens. If a property name does not meet these criteria, it can only be accessed using square bracket notation. This method is particularly handy for situations where property names are determined dynamically at runtime.

Answer №2

In JavaScript, objects have the ability to use keys as strings, which are then converted with coercion.

var object = {
  .12e3: 'wut'
};
object[.12e3]; // 'wut'
object['.12e3']; // undefined
object['120']; // 'wut'

To work with numeric values, it is recommended to use maps instead of objects. Learn more about maps here.

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

Step-by-step guide on incorporating Google Fonts and Material Icons into Vue 3 custom web components

While developing custom web components with Vue 3 for use in various web applications, I encountered an issue related to importing fonts and Google material icons due to the shadow-root. Currently, my workaround involves adding the stylesheet link tag to t ...

transition effect of appearing and disappearing div

Having trouble creating a fade out followed by a fade in effect on a div element. The fade out happens too quickly and the fade in interrupts it abruptly. Here is the JavaScript code: $('#fillBg').stop(true,false).fadeTo(3000, 0); $("#fillBg"). ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Ways to retrieve the global state from within the mutation namespace module

Within my state, I have organized two namespace modules: portfolio and stocks. The structure looks like this: export default new Vuex.Store({ modules: { stocks, portfolio } }) The stocks module contains a property called stocks, while the por ...

Tips for adjusting the color of the white tick in Material UI Checkbox with React and JavaScript

I'm currently attempting to customize the default white tick (not the checkbox background!) and change it to a different color that I choose. While I have come across solutions for earlier versions of MUI and React, I am specifically looking for a sol ...

AngularJS fails to recognize Iframe element during REST request

I'm having trouble with my webpage only reading the Iframe tag. It's sending the content correctly according to Postman. Postman is giving me this content: "Conteudo": "<p>Test iframe:</p>\n\n<p><iframe framebord ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

Incorporating JavaScript variables to enhance HTML attributes

Currently utilizing Backbone.js and in search of a solution to convert my data into hidden elements within a form for submission, as well as turning the data into values for textboxes. I am seeking a reliable solution that can effectively handle all speci ...

The extension's script initiates without waiting for the entire page to finish loading

Recently, I have embarked on developing a chrome extension that requires waiting for a YouTube page to fully load before inserting a button into the existing code. Despite using getElementById() to locate the element, the script often completes execution b ...

How can complex POST parameters be structured in a RESTful API?

For my current project, I am working on developing an application utilizing node.js along with express. This application involves a feature that allows users to subscribe to lists of items. Each subscription includes specific options such as minimum scores ...

Encountering the "Invalid JSON primitive" issue when making an AJAX request in MVC

Despite my efforts to resolve the "Invalid JSON primitive" issue by reading various references, I have not been able to find a solution. As a last resort, I am sharing my code in its simplest form and still encountering the error. See below for the minimal ...

Creating a JavaScript anchor through a backend bean function

Is it crazy to want to create an anchor that can be called from a backing bean method using JavaScript? I need to do this for specific reasons, utilizing a commandButton with ajax set to false. I'm attempting the following approach: RequestContext.g ...

What is the best way to delete an item (using its specific identifier) from an array within a mongoose/mongoDB model?

In my app, I have a User schema with a favorites key that stores an array of objects, each with a unique id. I am attempting to delete one of these objects based on its id. Here is the code snippet that I believe should accomplish this: User.updateOne({id ...

The passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...

Issues with JQuery Radio button selection in Internet Explorer 6

Here is some code that I am working with: <input type="radio" name="HotelSearch_Measure" value="Miles"> <input type="radio" name="HotelSearch_Measure" value="KM"> While this code functions properly in IE9, Chrome, and Firefox, it does not wor ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...

Strange behaviors when using setinterval with classes

Currently working on enhancing a slider functionality, and I have observed that everything is functioning smoothly - function Slider(element) { this.i = 0; this.element = element; var self = this; this.timer = window.setInterval(functi ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

Combine various hierarchies using a single JSON with d3.pack

I currently have a JSON file that I need to utilize in order to create three distinct hierarchy visualizations using d3.pack. This JSON file contains data for eventA (1 or 0) and eventB (1 or 0). Each individual leaf also possesses a unique ID. The hiera ...