Basic Question about Arrays

Hey there, I’m just learning about Arrays and I’m wondering why we need to use [ ] when declaring the arrays originally but when adding to an array we don’t need to use the [ ].

Example:

let names = [‘Mark’, ‘Will’];

names[2] = ‘John’;

console.log(names);

Why isn’t ‘John’, [‘John’]?

The use of [ ] signifies that whatever piece of data is an array so you need it when initially creating the array to signify that it is, in fact, an array. You don’t however need it when adding to the array because “John” is not an array with a string in it, it’s just a string. For the example you send, if there we’re [ ] around “John”, the end value of the array would be this:

names[2] = ["John"]

-> ["Mark", "Will", ["John"]]

Wheras without gets the intended result of:

names[2] = "John"
-> ["Mark", "Will", "John"]

Thank you for that explanation, I know this wasn’t a problem but I hate going through material without fully understanding simple things like these that probably get overlooked. As I learn I’m sure I will have a ton more simple questions like this.

1 Like