Home > Mobile >  Can someone confirm below array is a valid javascript array?
Can someone confirm below array is a valid javascript array?

Time:07-18

We mainly write object or string in an array like this -

const arr = [{id: 123}, 'test']

And then we can access it through the index of the item -

console.log(arr[0], arr[1]);

But is it a valid array if we do like this -

const arr = [];
arr['id'] = {message: 'Hello'};
arr['name'] = 'test';

Because it doesn't giving any error and still i can access the items through -

console.log(arr['id'], arr['name'])

CodePudding user response:

Arrays in JS are sequence of elements that you can access with its indexes.

const arr = [{id: 123}, 'test']

So here arr contain two elements {id: 123} at index 0 and 'test' at index 1.

So, you can access array elements using indexes as:

console.log(arr[0], arr[1]);

const arr = [{ id: 123 }, 'test'];
console.log(arr[0], arr[1]);


Also, Array is an object also so you can perform all sort of opertion on arrays that you can do with an object also

like assigning value to an object that you are doing here as:

arr['id'] = {message: 'Hello'};
arr['name'] = 'test';

accessing value from an array(object) as:

console.log(arr['id'], arr['name'])

No one is stopping you to use arrays as an object. But it is not recommended.

  • Related