-5

Please explain if anybody faced this issue, why we get 4 in result when we adding values in quotes and without them? "1" + 2 = 4?

It seems like js simply multiply the value in the key with no quotes

let obj = {
    "0": 1,
    0: 2
};

console.log(obj["0"] + obj[0]);
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • 7
    because if you console.log the object you'll see that you have one property only having the value 2.. property names are string so you set twice the same property – Diego D Dec 12 '22 at 08:25
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#property_names – robertklep Dec 12 '22 at 08:27
  • Object keys are always strings, if you set a key as a number or another datatype, it is implicitly converted to a string. Due to this, setting `0: 2` overrides `"0"` property. – Teemu Dec 12 '22 at 08:27
  • Does this answer your question? [Is there any way to use a numeric type as an object key?](https://stackoverflow.com/questions/3633362/is-there-any-way-to-use-a-numeric-type-as-an-object-key) – Ivar Dec 12 '22 at 08:38

2 Answers2

5

You set the same property twice. 0 and "0" are the same, so the last one will take effect.

You'll see this if you log the object:

let obj = {
    "0": 1,
    0: 2
};

console.log(obj); // {0: 2}
Mads Akselsen
  • 249
  • 1
  • 5
0

In javascript object is a type of variable that has the capability of storing data as a property and its value.

let obj = {
   0: "value"
}

//is the same as

let obj = {
   "0": "value"
}

//and vice-versa.

let obj = {
    "0": 1,
    0: 2
};

console.log(obj); // {0: 2}

in this code block, you write different values for the same property "0". so, the last value you used will be the value for the property "0" (i.e 2).

//In simple, you are writing 
let obj = {
   "0": 2
}
//
let obj = {
    0: 2,
    "0": 1
};
//if you use this code template
console.log(obj[0]); //will give an object {0 : 1}