array vs object in javascript

  • Share this:

In JavaScript, an array is an ordered collection of values. It is a data structure that allows you to store and access a list of items in a single place. You can create an array by enclosing a comma-separated list of values in square brackets `[]`.

Here is an example of an array that stores a list of numbers:

const numbers = [1, 2, 3, 4, 5];

You can access the elements of an array using their index, which is the position of the element in the array. Array indices are zero-based, meaning that the first element has an index of `0`, the second element has an index of `1`, and so on.

console.log(numbers[0]); // Output: 1
console.log(numbers[1]); // Output: 2
console.log(numbers[2]); // Output: 3

In JavaScript, an object is a collection of key-value pairs. It is a data structure that allows you to store data in a flexible and organized way. You can create an object using the object literal syntax, which consists of a set of curly braces `{}` containing a comma-separated list of key-value pairs.

Here is an example of an object that represents a person:

const person = {
  name: 'John',
  age: 30,
  gender: 'male'

You can access the properties of an object using dot notation or bracket notation.

console.log(; // Output: 'John'
console.log(person['age']); // Output: 30

In general, arrays are used to store lists of items, while objects are used to store collections of key-value pairs. Arrays are ideal for storing data that can be represented as a list, while objects are more suitable for storing data in a more structured and organized way.


About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.