Using Objects in JavaScript

Using Objects in JavaScript

What is an object and how do you access them?

·

3 min read

Arrays are ordered collections of data that we can use to store multiple items. They do have their limitations, however.

const student = ['John', 'Computer Science', 25, 'Doe'];

The array is stored in a variable called student which relates to the characteristics of a person. The problem with this, however, is that it's difficult to know which characteristic each element in the array relates to, as well as this we can only access each element of the array by its index.


What is an Object

Instead of this, we could use a JavaScript object to store the values instead. An object consists of key-value pairs called properties. Below I've written the same array as an object instead. Notice that it's now much easier to see what characteristic each value relates to.

const student = {
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  subject: 'Computer Science',
};

How to Access Objects

Dot notation

We can access the values within an object by looking up the respective property key. Let's take the same object we had before.

const student = {
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  subject: 'Computer Science',
};

We can get the value 'John' by using the property key firstName as follows.

student.firstName; // equals 'John'

Here we've taken the object student and used dot notation followed by the property key firstName to access the property value 'John'. If we were to try accessing a property key that doesn't exist on the object then this would return undefined.

const student = {
  firstName: 'John',
  lastName: 'Doe',
  age: 25,
  subject: 'Computer Science',
};

student.college; // equals undefined

Bracket Notation

As well as dot notation you can also use variables within square brackets to access property values like the example below. This is known as bracket notation.

const studentGroup = {
  'John': 'Maths',
  'Sally': 'Business',
  'Bob': 'Computer Science',
};
const name = 'Bob';

studentGroup.name; // equals undefined
studentGroup[name]; // equals 'Computer Science'

The reason studentGroup.name equals undefined is that for dot notation it will search for a property key called exactly name, which in this case doesn't exist. Whereas with bracket notation it searches for a property key equal to the variable name which does exist.


Conclusion

Objects come up a lot when using JavaScript so it is important to get comfortable using them. There will be times when it is more suitable to use an Object rather than an Array and you will become more adept at knowing when this is with practice. Generally, if you have an array that has values in it of different types then this would probably be better represented as an Object. This is one such example but there are plenty more. Happy coding!