Objects

This Scrimba screencast was created by Dylan C. Israel.

Objects give us the ability to group things together in a more descriptive way.

Every time we applied an attribute or style on an element, we were interacting with an object. ".setAttribute()" is a method contained in that object.

Let's take a look at how we can start to use objects to better organize our code.

Basic Object Structure

Objects are opened and closed within curly braces. Each property inside is separated by a comma. If the value is a string it needs to be contained inside quotes otherwise objects can support numbers, booleans, functions, arrays and other objects. Here's an object with each supported property.

Accessing Object Properties

Every property inside our object acts as a reference to the value associated with it. It might be more helpful to think of properties as variables that you define to let you know more about the contents inside. When we refer to my_string property in myObject, we are working with the value "This is a string".

There are two methods to accessing properties in an object, dot notation and bracket notation. Both methods are demonstrated below.

Calling a Function in an Object

We call a function in an object using the dot notation. Remember functions are executed with parenthesis ().

Accessing Nested Object Properties

An object can be a property of an object, create a nested object property. While nested object properties are little more complicated, we can still just use the dot or bracket notation by just adding another dot or bracket.

The following example just shows the dot notation, printing the value of the nested object property "another_property".

Updating Values of Object Properties

Any properties inside our objects can be modified, replaced, or removed. Once we have the value we can change it however we would like.

In this first example, we update the value of my_number inside myObject from 12 to 100.

Here we are pushing a new item into my_array inside myObject

Adding New Properties to an Object

Adding new properties to an object is easy. It's the same syntax we would use to modify a property, but if that property doesn't exist it will be created as a new property. In this example we add "new_property" to "myObject" after the object was defined.

Here we are adding a new method to our object. This method will return a number multiplied by itself. 2 * 2 = 4.

When a function is inside an object we refer to that function as a method.

Deleting Properties Inside an Object

We can also remove properties with the delete keyword.