JavaScript Arrays vs Objects

Kevin Peery
2 min readFeb 14, 2019

--

Both arrays and objects are types of JavaScript data structures. Their building blocks are numbers, Booleans and strings.

Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties. An object property is an association between a name (or key) and a value. If the property’s value is a function, it is known as a method. In the example below the object is named cat. The keys in the object are name, legs, tails, and enemies. The values of the object are “Whiskers”, 4, 1 and an array, [“Water”, “Dogs].

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Here’s a sample object:

var cat = {
name: “Whiskers”,
legs: 4,
tails: 1,
enemies: [“Water”, “Dogs”]
};

Objects are useful for storing data in a structured way and can represent real-world objects, like a cat. The cat object above is created using ({}) curly bracket syntax, which is called an object literal. Notice that each key is followed by a colon (:), and each key/value pair is separated by a comma (,). The keys in the object literal above do not have quotation marks ( “ ) or ( ‘ ) because there is no space or period in the key. If there is a space or period in the key, then quotation marks would be needed as shown below:

var cat = {
“feline name”: “Whiskers”,
“leg number”: 4,
“tail number”: 1,
enemies: [“Water”, “Dogs”]
};

To iterate over an object, you can use the for…in statement, while with an array you could use the for…of loop to iterate over iterable objects.

To set a blank object you can do something like this:

var person = { };

or

var person = { name: 'Kevin', age: 29 };

To access the properties of an object:

person.nameperson['name']

To modify properties:

person.name = 'Bill';
// => { name: 'Bill', age: 28 }
person.hobby = 'Dancing';
// => { name: 'Nancy', age: 30, hobby: 'Dancing' }

To access an array item, you use the bracket syntax. For example, let’s say you have the following:

let fruits = [ ‘Orange’ , ‘Pear’ ]

To access ‘Pear’ you would type fruits[1], keeping in mind that arrays are zero-indexed which means that they start with 0.

These are just a few of the many differences between Javascript arrays and objects.

--

--

No responses yet