Web Analytics

JavaScript Objects

Beginner ~15 min read

What are Objects?

In real life, a car is an object. A car has properties like weight and color, and methods like start and stop.

In JavaScript, objects are variables too. But objects can contain many values.

HTML
CSS
JS

Accessing Properties

You can access object properties in two ways:

  • objectName.propertyName (Dot notation)
  • objectName["propertyName"] (Bracket notation)
HTML
CSS
JS

Object Methods

Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.

HTML
CSS
JS
The this Keyword: In an object method, this refers to the object itself. In the example above, this.firstName means the firstName property of this object.

Adding and Deleting Properties

You can add new properties to an existing object by simply giving it a value. You can delete properties using the delete keyword.

HTML
CSS
JS

Summary

  • Objects are containers for named values called properties.
  • Methods are functions stored as object properties.
  • Properties can be accessed via dot notation or bracket notation.
  • this refers to the owner of the function.

Quick Quiz

How do you access the property 'color' of object 'car'?

A
car(color)
B
car['color']
C
car.color
D
Both 2 and 3