Skip to content

JavaScript Objects

In JavaScript, objects are fundamental. They are collections of key-value pairs, where keys are strings (or Symbols) and values can be any data type, including other objects or functions.

Real-World Analogy: Objects, Properties, and Methods

Section titled “Real-World Analogy: Objects, Properties, and Methods”

Think of a real-world object, like a car. A car has:

  • Properties: Characteristics like color, model, weight, current speed.
  • Methods: Actions it can perform, like start, accelerate, brake, stop.

Different cars (instances) will have the same set of properties and methods, but the values of their properties (e.g., color) will differ, and methods will operate on that specific car.

JavaScript variables can hold simple data values (primitives like numbers or strings):

let carName = "Volvo";

Objects, however, can hold many values, organized as named properties.

The most common way to create an object is using an object literal:

const car = {
make: "Toyota",
model: "Camry",
year: 2023,
color: "blue",
isRunning: false
};

The values are written as name: value pairs (or key: value), separated by commas. Property names can be unquoted if they are valid JavaScript identifiers. If they contain spaces or special characters, or are reserved words, they must be quoted.

const person = {
"first name": "John", // Quoted key due to space
lastName: "Doe",
age: 30,
"eye-color": "brown" // Quoted key due to hyphen
};

You can access object properties in two ways:

  1. Dot Notation: objectName.propertyName
console.log(car.make); // Output: Toyota
console.log(person.lastName); // Output: Doe
  1. Bracket Notation: objectName["propertyName"] (property name as a string)
console.log(car["model"]); // Output: Camry
console.log(person["first name"]); // Output: John (Bracket notation needed for keys with spaces/special chars)
// Bracket notation also allows using a variable for the property name:
let propertyKey = "color";
console.log(car[propertyKey]); // Output: blue

You can change the value of an existing property or add a new property using assignment:

const myComputer = {
brand: "Apple",
type: "Laptop"
};
// Modify an existing property
myComputer.type = "MacBook Pro";
console.log(myComputer.type); // Output: MacBook Pro
// Add a new property
myComputer.year = 2023;
console.log(myComputer.year); // Output: 2023
myComputer["ram_gb"] = 16;
console.log(myComputer.ram_gb); // Output: 16
console.log(myComputer); // { brand: "Apple", type: "MacBook Pro", year: 2023, ram_gb: 16 }

Methods are functions stored as object properties. They define actions an object can perform.

const personWithMethods = {
firstName: "Jane",
lastName: "Doe",
age: 28,
// Method to get full name
fullName: function() {
return this.firstName + " " + this.lastName;
},
// ES6 shorthand method syntax
greet() {
console.log("Hello, my name is " + this.fullName() + " and I am " + this.age + " years old.");
}
};

Inside an object method, this refers to the object itself (the object the method was called on). This allows methods to access and manipulate the object’s own properties.

You call an object method using dot notation followed by parentheses ():

const name = personWithMethods.fullName();
console.log(name); // Output: Jane Doe
personWithMethods.greet(); // Output: Hello, my name is Jane Doe and I am 28 years old.

If you access a method property without (), it returns the function definition itself, not the result of calling the function:

const greetFunction = personWithMethods.greet;
console.log(greetFunction); // Output: [Function: greet] (or similar, shows the function definition)

You can loop through an object’s properties using various methods:

const user = {
id: 101,
username: "coder",
email: "coder@example.com",
isActive: true
};
// for...in loop (iterates over enumerable properties, including inherited ones)
console.log("Using for...in:");
for (const key in user) {
if (user.hasOwnProperty(key)) { // Good practice to check for own properties
console.log(`${key}: ${user[key]}`);
}
}
// Object.keys() (returns an array of an object's own enumerable property names)
console.log("\nUsing Object.keys():");
Object.keys(user).forEach(key => {
console.log(`${key}: ${user[key]}`);
});
// Object.values() (returns an array of an object's own enumerable property values)
console.log("\nUsing Object.values():");
Object.values(user).forEach(value => {
console.log(value);
});
// Object.entries() (returns an array of an object's own enumerable [key, value] pairs)
console.log("\nUsing Object.entries():");
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});

JSON is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. Its syntax is derived from JavaScript object literal syntax, but with some differences (e.g., keys must be double-quoted strings in JSON).

JavaScript provides built-in methods to convert between JavaScript objects and JSON strings:

  • JSON.stringify(object): Converts a JavaScript object to a JSON string.
  • JSON.parse(jsonString): Parses a JSON string, constructing the JavaScript value or object described by the string.
const book = {
title: "The Art of Programming",
author: "Dev Master",
pages: 300,
published: true
};
// Convert object to JSON string
const jsonBook = JSON.stringify(book);
console.log(jsonBook); // Output: {"title":"The Art of Programming","author":"Dev Master","pages":300,"published":true}
// Convert JSON string back to object
const bookObject = JSON.parse(jsonBook);
console.log(bookObject.title); // Output: The Art of Programming

While JavaScript allows creating wrapper objects for primitive types like strings, numbers, and booleans using constructors (e.g., new String("text"), new Number(123)), this is generally discouraged.

let x = new String("John"); // x is an object
let y = "John"; // y is a string primitive
console.log(typeof x); // "object"
console.log(typeof y); // "string"

Using these wrapper objects complicates your code, can lead to unexpected behavior (e.g., new String("") is truthy), and can slow down execution. Always prefer using primitive values directly.

JavaScript automatically converts primitives to objects when a method is called on them (autoboxing), so you can still use methods like y.toUpperCase().

Objects are a vast and essential part of JavaScript. Other ways to create objects include constructor functions and ES6 classes, which are used for more complex object-oriented programming patterns.