JavaScript Objects
JavaScript Basics

JavaScript Objects

JavaScript Objects

Let's learn more about JavaScript Objects.

Real Life Objects, Properties, and Methods

In JavaScript, an object is a great way to represent a real-life entity like a car because it allows you to encapsulate properties and methods associated with that entity in a single, organized structure.

JavaScript Object Example: Car

  • Properties: These are characteristics associated with an object. For a car, the properties can include its name, model, weight, and color. Each car object can have different values for these properties.
let car = {
  name: "Fiat",
  model: "500",
  weight: "850kg",
  color: "white"
};

Methods: These are actions that the car can perform. Methods in an object are defined as functions. A car might have methods like start, drive, brake, and stop. Each method performs actions using or modifying the object's properties.

let car = {
  name: "Fiat",
  model: "500",
  weight: "850kg",
  color: "white",
  start: function() {
    console.log("Car is starting");
  },
  drive: function() {
    console.log("Car is driving");
  },
  brake: function() {
    console.log("Car is braking");
  },
  stop: function() {
    console.log("Car has stopped");
  }
};

Usage in Code: Accessing properties and methods of a car object is straightforward:

  • Accessing properties: console.log(car.name); // Outputs: Fiat
  • Calling methods: car.start(); // Outputs: Car is starting

This structure reflects how objects in JavaScript not only store data (properties) but also encapsulate procedures (methods) that interact with that data, mirroring the way objects behave in the real world.

JavaScript Objects

While a simple variable can hold a single data value, objects allow you to group multiple data values and functionalities into a single entity.

Example with a Simple Variable:

  • Assigning a simple value to a variable
let car = "Fiat";  // Here, 'car' is just a string variable holding the value "Fiat".

This approach is straightforward but limited because the variable car can only hold one attribute of a real-world car, which is its brand or model name. In contrast, using an object allows you to encapsulate more detailed information and methods related to the car.

Expanding to an Object:

  • Creating an object to represent a car more comprehensively
let car = {
  make: "Fiat",
  model: "500",
  weight: "850kg",
  color: "white",
  start: function() {
    console.log("The car has started.");
  }
};

In this object car, properties such as make, model, weight, and color store data about the car, while the start method (a function within an object) allows for actions pertaining to the car to be executed. This object-oriented approach provides a more flexible and realistic way to handle data in programming.

In JavaScript, objects serve as powerful variables capable of holding multiple values under a single name. This makes them ideal for representing real-world entities that possess various attributes.

Example of an Object:

  • Creating an object that encapsulates multiple characteristics of a car
const car = {
  type: "Fiat",
  model: "500",
  color: "white"
};

In this example, the car object holds several values, each identified by a property name:

  • type: represents the brand of the car, "Fiat".
  • model: specifies the model, "500".
  • color: details the color, "white".

In JavaScript, when creating objects, the data is structured as name-value pairs, where each name (or property) is followed by a colon and then the value. This clear syntax helps organize and access data efficiently.

Object Definition

You define (and create) a JavaScript object with an object literal:

Example

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Spaces and line breaks are not important. An object definition can span multiple lines:

Example

const person = {
 firstName: "John",
 lastName: "Doe",
 age: 50,
 eyeColor: "blue"
};

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Object Properties

In JavaScript, the name-value pairs in objects are referred to as properties:

Example of Object Properties:

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
};

Each property consists of a key (like firstName) and its corresponding value ("John").

Accessing Object Properties

You can access the properties of an object in JavaScript in two main ways:

  1. Dot notation: Use the dot followed by the property name (e.g., objectName.propertyName).
  2. Bracket notation: Use the object name followed by the property name within quotation marks and square brackets (e.g., objectName["propertyName"]).

Example1

person.lastName;

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>

Example2

person["lastName"];

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>

Object Methods

Objects can include methods, which are actions executable on the objects themselves. Methods are essentially functions defined as properties within the object.

Example of an Object with Methods:

  • Here’s a layout of properties and a method in an object:
    • firstName: John
    • lastName: Doe
    • age: 50
    • eyeColor: Blue
    • fullName: A method defined as a function that returns the full name by combining firstName and lastName.

In this context, a method is simply a function that is stored as a property of an object.

Example

const person = {
 firstName: "John",
 lastName : "Doe",
 id       : 5566,
 fullName : function() {
   return this.firstName + " " + this.lastName;
 }
};

In the example above, this refers to the person object:

this.firstName means the firstName property of person.

this.lastName means the lastName property of person.

What is this?

In JavaScript, the this keyword represents the object that the function is a property of, but its context depends on how and where this is used:

  • Inside an object method: this points to the object itself.
  • Used alone or outside any function: this refers to the global object (in browsers, this is typically window).
  • Within a function: this also refers to the global object.
  • Within a function in 'strict mode': this is undefined.
  • During an event handling: this refers to the element that received the event.
  • With methods like call(), apply(), and bind(): this can be explicitly set to refer to a specific object.

This flexible yet specific behavior allows this to be adapted to different contexts within the code, depending on the particular needs of the function or method where it is used.

The this Keyword

In a function definition, the this keyword refers to the object that owns the function.

For example, if the fullName function is a property of the person object, this within the fullName function points to the person object itself. Therefore, this.firstName refers to the firstName property of the person object.

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example

name = person.fullName();

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>

If you access a method without the () parentheses, it will return the function definition:

Example

name = person.fullName;

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>If you access an object method without (), it will return the function definition:</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName;
</script>

</body>
</html>

Do Not Declare Strings, Numbers, and Booleans as Objects!

When you declare a JavaScript variable using the "new" keyword, you create an instance of an object:

  • x = new String(); creates x as an instance of the String object.
  • y = new Number(); creates y as an instance of the Number object.
  • z = new Boolean(); creates z as an instance of the Boolean object.

However, it's generally recommended to avoid creating String, Number, and Boolean objects as they can make the code more complex and reduce execution speed. More details about objects will be covered later in this tutorial.

Take a look into your desired course