2

Can someone explain what's going on in this JavaScript code:

    let arr = [];

    arr["foo"] = "11";
    arr["sd"] = "12";
    arr[1] = "13";

    console.log(arr.length); //2
    console.log(arr) // [empty, "13", foo: "11", sd: "12"]

Why is there an empty element in the array?

Also, why the Array length equals 2 and not 4?

1 Answer 1

6

Property names that are not numeric do not count towards the length of an array in JavaScript. By setting arr[1] you force the length to be 2, because the length is always one greater than the maximum numeric property name. Thus your array implicitly has an empty element 0, an element 1 with a value, and then two other properties with string keys.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that "numeric" property names must be positive integers that fit in 31 bits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.