Array is an object that stores values by numeric indices (0, 1, 2…). Object is a collection of key-value pairs, where keys can be any strings. Main difference: arrays are ordered and work with numeric indices, while objects work with named keys.
Arrays and objects are two main ways to store data in JavaScript. They are similar, but have important differences.
Array stores data by numeric indices:
const fruits = ['apple', 'banana', 'orange'];
// Indices: 0 1 2Object stores data by named keys:
const user = {
name: 'John',
age: 25,
city: 'Moscow'
};// List of similar elements
const students = ['John', 'Peter', 'Mary'];
const numbers = [1, 2, 3, 4, 5];// Description of one entity with different properties
const car = {
brand: 'Toyota',
model: 'Camry',
year: 2020
};typeof [] // 'object'
typeof {} // 'object'const arr = [1, 2, 3];
const obj = { a: 1 };
// Changes visible everywhere there is a reference// ❌ Bad - list of users as object
const users = {
0: { name: 'John' },
1: { name: 'Peter' }
};
// ✅ Good - list of users as array
const users = [
{ name: 'John' },
{ name: 'Peter' }
];// ❌ Mixing array and object
const data = [];
data.name = 'John'; // Don't do thisUnderstanding the difference between arrays and objects helps properly structure data and write clearer code.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪