What is the difference between an object and an array?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Objects #Arrays #JS Basics

Brief Answer

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.


Full Answer

Arrays and objects are two main ways to store data in JavaScript. They are similar, but have important differences.

What is an Array

Array stores data by numeric indices:

const fruits = ['apple', 'banana', 'orange'];
// Indices:     0       1        2

What is an Object

Object stores data by named keys:

const user = {
  name: 'John',
  age: 25,
  city: 'Moscow'
};

Main Differences

1. Storage Method

  • Array: values by numeric indices (0, 1, 2…)
  • Object: values by string keys (name, age, city…)

2. Element Order

  • Array: preserves element order
  • Object: order not always guaranteed (in old browsers)

3. Length

  • Array: has length property
  • Object: no length, but keys can be counted

4. Special Methods

  • Array: push, pop, shift, unshift, map, filter…
  • Object: Object.keys, Object.values, Object.entries…

Usage Examples

When to Use Array

// List of similar elements
const students = ['John', 'Peter', 'Mary'];
const numbers = [1, 2, 3, 4, 5];

When to Use Object

// Description of one entity with different properties
const car = {
  brand: 'Toyota',
  model: 'Camry',
  year: 2020
};

What They Have in Common

Both are Objects

typeof [] // 'object'
typeof {} // 'object'

Both Passed by Reference

const arr = [1, 2, 3];
const obj = { a: 1 };
 
// Changes visible everywhere there is a reference

Simple Rules

Use Array When:

  • Need to store list of similar elements
  • Element order matters
  • Working with numeric indices

Use Object When:

  • Need to describe one entity with different properties
  • Working with named fields
  • Want to structure data

Common Mistakes

1. Wrong Structure Choice

// ❌ 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' }
];

2. Mixing Approaches

// ❌ Mixing array and object
const data = [];
data.name = 'John'; // Don't do this

Key Points

  1. Arrays — for lists of similar data
  2. Objects — for structured data with different properties
  3. Both passed by reference — be careful with changes
  4. Different methods — arrays have their methods, objects have their own
  5. Both are objects — in JavaScript everything is objects (except primitives)

Understanding 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 💪