HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Objects

Objects are variables too, but they can contain multiple values. In real life, a car is an object. A car has properties like weight and color, and methods like start and stop.


Object Definition

You define (and create) a JavaScript object with an object literal using curly braces {}.

const person = {
  firstName: "Mim",
  lastName: "Akter",
  age: 25,
  eyeColor: "brown"
};

Object Properties

The name:value pairs in JavaScript objects are called properties.

Property Property Value
firstName "Mim"
lastName "Akter"
age 25

Accessing Object Properties

You can access object properties in two ways:

1. Dot Notation (.)

This is the most common and readable way.

console.log(person.firstName); // "Mim"

2. Bracket Notation ([])

This is useful if the property name is stored in a variable or contains spaces.

console.log(person["firstName"]); // "Mim"

Object Methods

Objects can also have methods. Methods are actions that can be performed on objects. A method is simply a property containing a function definition.

const person = {
  firstName: "Mim",
  lastName: "Akter",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName()); // "Mim Akter"
What is 'this'? In a function definition, this refers to the "owner" of the function. In the example above, this is the person object.

Key Points to Remember

  • Objects are collections of properties and methods
  • Properties are written as name:value pairs
  • Access properties using dot notation or bracket notation
  • Methods are functions stored as object properties
  • The this keyword refers to the current object
  • Always use const when declaring objects as standard practice