'what is basic difference between the array and objects in the java-script [closed]

In using the react i'm not able to understand in which situations we prefer array over objects sometimes we are using objects and sometimes we are using arrays that thing make me little bit confuse



Solution 1:[1]

Objects are mutable data structure in javascript which is used to represent a ‘Thing’. This could be anything like plants, cars, person, community etc.It stores the data in key value pair and the key can be anything except for undefined. The keys are iterable and can be accessed in any order.

We can either use a dot operator followed by key name obj.name or a square bracket along with key in string format obj['name'] to access the value.

const obj = {
  name: 'Shubham Shukla',
  age: '22',
  gender: 'Male',
  getDetails: function() {
    return `${this.name} is ${this.age} years old`;
  }
};

console.log(obj.name);

Arrays are objects only in javascript. The major difference is that they store the data in an ordered collection in which the data can be accessed using a numerical index.They are also mutable and data can be modified at any index. Indexes are zero based which means the first item is stored at Oth index, second at first and so on, last item is stored at n-1th index.

const arr = [22, 17, 34, 45, 78, 67];

console.log(arr[0]);

if you have to store the data in order or in a sequence then use array otherwise you can use object for everything else.

Solution 2:[2]

Most of the cases, you're gonna use objects for named items, while array for just a collection of items.

Example which uses both:

var someone = {
  full_name: ['Bob', 'Smith'],
  age: 32,
  gender: 'male
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy
Solution 2 Marco Antonio