Objects

JavaScript objects are incredibly versatile data collections. Object literals—often referred to as POJOs, or “Plain Old JavaScript Objects”—are typically used to store data in key-value pairs, much like a dictionary in Python or a map in Go.

Creating an Object

You create an object using curly braces {} and define its properties using the key: value syntax.

const apple = {
  name: "Apple",
  radius: 2,
  color: "red",
};

Accessing Properties

You can easily access the properties stored on an object using the dot operator (.).

console.log(apple.name); // Output: "Apple"
console.log(apple.radius); // Output: 2
console.log(apple.color); // Output: "red"

Practical Example

Objects are perfect for bundling related data together so you can pass it around your program as a single entity.

function createMessage(phoneNumber, message) {
  return {
    phoneNumber: phoneNumber,
    message: message,
    messageLength: message.length
  };
}

const myMsg = createMessage("555-1234", "Hello there!");
console.log(myMsg.messageLength); // Output: 12

While we use them as basic key-value stores here, JavaScript objects are highly advanced and act as the foundation for classes and prototypes, which we will explore later.