JS Object Types

JavaScript Object Data Type

The object data type is the only non-primitive type in JavaScript. While a primitive type can only store a single, simple value (like a string or a number), an object can be used to store a collection of keyed data and more complex entities.


1. What is an Object?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a primitive value, another object, or even a function (which is then known as a method).

Object Literal Example

const car = {
  make: "Ford",
  model: "Mustang",
  year: 1969,
  start: function() {
    console.log("Engine started!");
  }
};

console.log(car.model); // "Mustang" car.start(); // "Engine started!"


2. Everything Can Be an Object

In JavaScript, almost everything can behave like an object.

Even primitives can behave like objects when you try to access their properties or methods. JavaScript temporarily wraps the primitive in an object to execute the method.

Primitives Behaving Like Objects

let text = "Hello World!";

// Accessing the 'length' property of a string primitive console.log(text.length); // 12

// Calling the 'toUpperCase()' method on a string primitive console.log(text.toUpperCase()); // "HELLO WORLD!"


3. Pass-by-Value vs. Pass-by-Reference

The most important difference between primitive types and object types is how they are stored and passed around in your code.

Pass-by-Reference Example

// Create an object
const person1 = { name: "John" };

// Assign person1 to person2. Both now point to the SAME object. const person2 = person1;

// Change the name using person2 person2.name = "Jane";

// The change is reflected in person1, because they are the same object! console.log(person1.name); // "Jane"


Exercise

?

In JavaScript, how are object data types passed when assigned to a new variable?