0

In JavaScript, when adding a property to an existing object like this:

var qBacks = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

qBacks["4"] = "Brett Favre"; //Will work!
qBacks.4 = "Brett Favre"; //Will not work!
//but
qBacks.player4 = "Brett Favre"//Will work.

and, if I want to append property 4 to remove the first name, I have to use bracket notation to complete:

qBacks[4] = "Farve"; //Works!
qBacks.4 = "Farve"; //Will not work!

Why won't the dot operator work with numbers to dynamically add properties or to modify the value? I am guessing it has something to do with typeof 4 being a primitive but would like to get better understanding. Thanks

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 1
    dot path syntax only works on names that start with letters (or _) and contain only `/\w/` chars – dandavis Jan 27 '16 at 17:36
  • It is necessary, because the `.` can be ambiguous. Let’s say you had not one level, but two – now what would `object.4.5` address then? Would it be a “first-level” property with the name `4.5`, or would it perhaps be a property named `4`, that is itself an object and has a property with name `5` beneath it …? – CBroe Jan 27 '16 at 17:39

1 Answers1

1

A numeric key on objects will always be converted into a string. This is done in step 6 of the ECMAScript Property Accessor (§11.2.1) algorithm.

This was already answered here

var foo = {};
foo[4] = 'bar';

console.log(foo[4] === foo["4"]); // returns true
Community
  • 1
  • 1
Jörn
  • 845
  • 5
  • 16