JavaScript objects and arrays explained

New tutorials sent to your inbox 💌
rolling doodle
Prerequisites
This tutorial assumes that you are familiar with JavaScript variables and data types.
What is an object?
An object in JavaScript is a data type used for storing a collection of properties that define a "thing". Continuing on from our calculator project, a good example would be to create an object for our expense with the properties category and amount. The syntax will look like this:
const expense = {
  category: 'food',
  amount: 50
}
An object is represented by curly braces and contains key-value pairs. Each key gives you reference to its value and its value can be of any data type.
Getting a property's value
Let's declare the expense object and display the value of each property using the dot notation. This is when you write the name of the object and then use a . to access its property name. E.g. expense.category
Category: food
Amount: 50
Setting a property's value
Previously we talked about how using the keyword let allows us to reassign different values to a variable. This is however an exception for more complex data types like objects, arrays and functions. For now, just know we can set new values to objects that are declared with a const like so:
category: bills
expense amount: 100
We can also update a property's value by retrieving it using the bracket notation.
category: bills
expense amount: 100
Deleting a property's value
We can also delete a property from an object using the keyword delete.
category:
expense amount: 50
Introducing arrays
In the tutorial on conditional statements, we wrote an if statement to calculate if we were ramen profitable for the month by seeing if monthly revenue > minimum expenses.
Expenses: 450
Revenue: 2000
result: Goal achieved! 🎉
This works in the example, but in the real world we would actually need to work out what the minimum expenses are first. We could do something like below, but we would need to repeat the same sets of variables for each month... 🙈
Expenses: 290
Revenue: 4000
result: Goal achieved! 🎉
Notice how we are using brackets to group operations we want to execute together in the condition. Now is probably a good time to refactor our code using an object instead. Refactoring means improving the structure and readability of our code without making any changes to its behaviour.
function RamenCalculator() {

  const expense = {
    month: 'January',
    foodExpenses: 50,
    billExpenses: 100
  }

  const revenue = {
    amount: 2000,
    month: 'January'
  }
}
Wait what? Won't I still need to declare another 11 expense objects for each month?! And this my friend is the perfect time to introduce the variable type array. An array is a data type used for storing a list of elements of any data type!

An array is declared using square brackets.
const emptyArray = []
To do: Try creating a list of strings and numbers in the editor below.
strings: HelloShootingUnicorns
numbers:
Let's turn our expenses and revenue into an array of objects! Note each object in the array needs to have the same key-pair value.
Hmm can we access an object?
Retrieving an element from an array
Retrieving an element from an array is a little different compared to retrieving values from an object. Each element in an array has an index that starts at 0.
function RamenCalculator() {
  const expenses = [
    { // index 0
      month: 'January',
      foodExpenses: 50,
      billExpenses: 100
    },
    { // index 1
      month: 'February',
      foodExpenses: 20,
      billExpenses: 90
    },
    { // index 2
      month: 'March',
      foodExpenses: 80,
      billExpenses: 40
    }
  ];
}
This means to access our March expenses we can do so like this.
March: 120
To do: Try getting the values for January.
Trying to access an element with an index that doesn't exist will throw an error. We can avoid this by checking how many items are in the array using the method .length() and deducting 1 from it (since indexes start at 0).
length: 3
And now for the moment you've all been waiting for... How can we sum all the expenses together for each month without writing spaghetti code? This is the perfect moment to segue into For loops! Stay tune :)
Lesson summary
Congrats you've made it to the end of the lesson on JavaScript objects and arrays 🎉

An object is a data type for storing a collection of properties.
We can get and set a property's value using the dot notation or the bracket notation.
We can delete a property's value using the delete keyword.
An Array is a data type used for storing a collection of elements of any data type.
An array is an ordered set of values you can refer to using an index.
To do: Next lesson on for loops
Next tutorial