Not able to get the flow the Js array

arr[“len1”, “len2”, “len3”]=“val3”
when i am accessing arr.len1 or arr.len3 i am getting undefined , WHEREAS, when im logging arr.len3 I am getting “val3” as output.

This is not how you access arrays. I think I can see how it’s working accidentally, if this is actually the code, but what you’ve written makes very little sense.

arr["len1", "len2", "len3"] = "val3"

If this is literally the code you’ve written, can you explain:

  1. what you are trying to do, and
  2. what you think this code is doing, and
  3. what you think this code should be doing.

Edit: just to explain what this is doing @anujvdev2020 (and you still need to answer the questions above, as I have no idea what it is you are trying to do here).

You have an object called arr. It might be an array or a plain object, I have no idea, I just assume it’s an array because you called it arr.

So I’ll declare that:

let arr = [];

That’s an object, currently looks like:

{
  length: 0,
}

Then three things:

  1. You can access object properties using square brackets or using the dot operator. So for example:
    arr.length // this is 0
    arr["length"] // same thing, this is 0
    
  2. You can assign properties to objects in a similar way:
    arr[0] = 10
    // arr is now { "0": 10, length: 1}
    // same as [10]
    arr["hi"] = "Hi"
    // arr is now { "0": 10, hi: "Hi", length: 1 }
    
  3. The comma operator (,) evaluates each value in turn and returns the last one.

So

arr["len1", "len2", "len3"]

Evaluate “len1”, then “len2”, then “len3”. They don’t do anything, they’re just strings. Last one gets returned

arr["len3"]

Assign the value “val3” to that

arr["len3"] = "val3"

arr looks like:

{
  len3: "val3",
  length: 0
}
2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.