0

var recordCollection = {
  2548: {
    albumTitle: 'Slippery When Wet',
    artist: 'Bon Jovi',
    tracks: ['Let It Rock', 'You Give Love a Bad Name']
  },
  2468: {
    albumTitle: '1999',
    artist: 'Prince',
    tracks: ['1999', 'Little Red Corvette']
  }
};


console.log(recordCollection[2548])

This is giving error:

console.log(recordCollection.2548)
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Katsura
  • 9
  • 2

2 Answers2

2

MDN has a great page on Working with objects that speaks directly to this (emphasis mine):

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

esqew
  • 42,425
  • 27
  • 92
  • 132
1

In javascript objects can have keys as string. They are converted to strings with coercion.

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

If you want to use numeric values you can use maps instead of objects. Read more about maps here: https://www.w3schools.com/js/js_object_maps.asp

Arun Bohra
  • 104
  • 1
  • 10