element index is string❗️

JSobjectbuilt-inArrayaccess ⟩ element index ⟩ is string

the type of element index is String, not Number

let obj = { };
let arr = [1,2,3];

obj["1"] = 'one';

let sum = 0;

for (let i in arr) {  // ⭐️ array index is 'string'
    log(i, typeof i)  // ❗ '0', 'string', ...
    sum += i;         // ❗ string concatenation, not number addition
}

obj["1"],    // 'one'
obj[1],      // 'one' (obj[1] converted to obj["1"])

arr[1],      // 2     (arr[1] converted to arr["1"])
arr["1"],    // 2

sum,         // ❗'0012'   (not 0+1+2 = 3)
typeof sum,  // ❗'string'

Last updated