Intro to objects

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Intro to objects

An object is a type of data. Objects are super important because you can only pass two types of data around as variables—primitives and objects.

What are objects?

An object is data that contains key-value pairs.

You can create objects by writing these key-value pairs within curly braces. If you intend to create multiple key-value pairs, you need to separate each pair with commas, like this:

const anObject = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  // ...
}

Each key gives you a reference to a value. If you imagine an English dictionary, the keys are the words while the values are the definition of each word.

const dictionary = {
  dream: "a series of thoughts, images, and sensations occurring in a person's mind during sleep",
  happy: "feeling or showing pleasure or contentment",
  // ...
}

Since object stores key-value pairs, another analogy you can use is to compare objects in JavaScript with objects in real life.

For example, you can observe the device you’re using to read this lesson. What device is this? What’s its size? What’s its operating system?

If you put this information together into a JavaScript object, it’d look like this:

const macbook = {
  operatingSystem: 'macOS Sierra',
  screenResolution: '2880x1800',
  screenSize: '15.4 inch',
  usbPorts: 2,
  storage: '512gb',
  // ... Other specs
}

Object values

Objects can contain any value that’s valid in JavaScript. This means you can store primitives (like Strings and Numbers) and other objects.

const anObject = {
  string: 'Yay',
  number: 1,
  boolean: true,
  anotherObject: {},
  aFunction: function () {}, // more on functions later
  anArray: [] // more on array in a future lesson
}

Getting the value of a property

Object keys are called properties. You can use two methods to get the value of a property.

The first method is through the dot notation, where you write the name of the object, followed by ., followed by the property name:

const prop = object.property

If you want to get the storage property of the macbook we declared above, you can write macbook.storage.

const macbookStorage = macbook.storage
console.log(macbookStorage) // 512gb

The second method is through the bracket notation, where you write the name of the object, followed by a string of the property in square brackets ([]).

const macbookStorage = macbook['storage']
console.log(macbookStorage) // 512gb

Both methods work.

Normally, you’ll use the dot notation. You’ll only use the bracket notation in special occasions where the dot notation doesn’t work. These special occasions include:

  1. When your property name is an invalid identifier
  2. When you need to get the value of a property through a variable

Invalid identifiers

Remember the four constraints you had when you declare variables?

  1. It must be one word
  2. It must consist only of letters, numbers or underscores (0-9, a-z, A-Z, _)
  3. It cannot begin with a number
  4. It cannot be any of these reserved keywords

Anything that follows these four rules is a valid identifier. Anything that doesn’t follow these rules is an invalid identifier.

Objects can have invalid identifiers as properties, like:

const objWithInvalidIdentifier = {
  'First Name': 'Zell'
}

When you have an invalid identifier, you can’t use the dot notation. You need to use the bracket notation:

const firstName = objWithInvalidIdentifier.First Name // Syntax Error: Unexpected identifier
const firstName2 = objWithInvalidIdentifier['First Name'] // Zell

Of course, when you create objects, try to make properties with valid identifiers so you can use the dot notation.

Getting the value of a property through a variable

If you need to get a property through a variable, you can use the bracket notation. Let’s go through this section with an example.

Let’s say you stored the property to search in a variable called propertyToGet.

const propertyToGet = 'storage'

You can’t use the dot notation to get propertyToGet because the macbook doesn’t contain a property called propertyToGet.

const storageWithDotNotation = macbook.propertyToGet
console.log(storageWithDotNotation) // undefined

To use propertyToGet, you need to use the bracket notation.

const macbookStorage = macbook[propertyToGet]

Here, JavaScript replaces propertyToGet with the variable you inserted, which means this happens:

const macbookStorage = macbook['storage']
console.log(macbookStorage) // 512gb

Setting the value of a property

You can set the value of a property either with the dot notation or the bracket notation. Likewise, the dot notation is always preferred.

// Dot notation
macbook.storage = '256gb'

// Bracket notation
macbook['usbPorts'] = 2

console.log(macbook)
// {
//   storage: '256gb',
//   usbPorts: 2
// }

Deleting properties

You can delete key-value pairs from objects with the delete keyword. To do so, you write delete, followed by the property either in dot or bracket notation.

delete object.property

Here’s an example where we delete the storage property from the macbook Object.

delete macbook.storage
console.log(macbook)
// The storage property is already deleted, hence you don't see it anymore when you console.log it
// {
//   usbPorts: 2
// }

Functions are Objects in JavaScript

Functions are a special kind of Object in JavaScript. They can have properties too (although you’ll probably not use them).

// You can add properties to functions
function sayName () {}
sayName.property = 'Hallelujah'

console.log(sayName.property)
// Hallelujah

Since functions are objects, you can write functions as object values. The properties that contain functions as their values are called methods.

const anObject = {
  aMethod: function () {
    // Do something in function
  }
}

In the following example, we say playMusic is a method of macbook.

const macbook = {
  playMusic: function () {
    /* some code to play music */
  }
}

Since methods are functions, they behave exactly like functions.

To call a method, you write parenthesis () after getting the method through the dot or bracket notation:

// Calling a method with the dot notation
macbook.playMusic()

// Calling a method with the bracket notation
macbook['playMusic']()

You can also add arguments to methods, just like normal functions:

const greeter = {
  sayHello: function (name) {
    console.log('Hello ' + name + '!')
  }
}

greeter.sayHello('Zell')
// Hello Zell!

You may hear phrases like “higher order functions” and “functions are first class objects” when you browse outside tutorials. Ignore these phrases. They both mean functions are objects, which means you can pass functions around as a variable. People like to introduce important-sounding jargons to make functions sound more amazing (and confusing) than they really are.

Exercise

Practice making objects. You need to use them a lot when you code for real. Do the following:

  1. Make an empty object.
  2. Make a property for your object that can be accessed with a dot notation. Get the value of this property.
  3. Make a property for your object that can only be accessed with the bracket notation. Get the value of this property.
  4. Set the value of a property with the dot notation.
  5. Set the value of a property with the square bracket notation.
  6. Make a method. Call this method.
  7. Make a method that takes in an argument. Call this method.

Answers

  • Make an empty object
const human = {}
  • Make a property for your object that can be accessed with a dot notation. Get the value of this property.
const human = {
  firstName: 'Zell'
}

// Accessing the `firstName` property
console.log(human.firstName) // Zell
  • Make a property for your object that can only be accessed with the bracket notation. Get the value of this property.
const human = {
  'first name': 'Zell'
}

// Accessing the `first name` property
console.log(human['first name']) // Zell
  • Set the value of a property with the dot notation
const human = {
  'firstName': 'Zell'
}

// Setting another property
human.lastName = 'Liew'

// Accessing the `lastName` property
console.log(human.lastName) // Liew
  • Set the value of a property with the square bracket notation
const human = {
  'firstName': 'Zell'
}

// Setting another property with bracket notation
human['lastName'] = 'Liew'

// Accessing the `lastName` property
console.log(human.lastName) // Liew
  • Make a method. Call this method
const human = {
  sayName: function () {
    console.log('My name is Zell')
  }
}

// Calling the method
human.sayName() // My name is Zell
// Shorter syntax to define a method
const human = {
  sayAge (age) {
    console.log('I am ' + age + ' years old')
  }
}

// Calling the method
human.sayAge(30) // I am 30 years old