Objects are a fundamental part of JavaScript and are used extensively in various programming scenarios. They allow you to store data in key-value pairs, making them versatile for representing real-world entities like users, products, or settings.
In this tutorial, we'll explore how to create objects using object literals, understand their properties, and learn two ways to access these properties: dot notation and bracket notation.
Objects in JavaScript are collections of key-value pairs. Each key is a string (or a Symbol), and each value can be any data type, including other objects or functions. Objects are essential for implementing object-oriented programming (OOP) concepts like encapsulation, inheritance, and polymorphism.
Understanding how to work with objects is crucial as they form the backbone of many JavaScript applications, from simple scripts to complex web applications.
An object literal is a way to create an object using curly braces {}. Inside these braces, you define properties in the format key: value.
1const person = {2name: 'Alice',3age: 30,4city: 'New York'5};
You can access the properties of an object using two main notations: dot notation and bracket notation.
Dot notation is the most common way to access object properties. It uses a period . between the object name and the property name.
1const person = {2name: 'Alice',3age: 30,4city: 'New York'5};67console.log(person.name); // Output: Alice8console.log(person.age); // Output: 30
Alice 30
Bracket notation allows you to access properties using a string expression, which can be useful when property names are dynamic or contain special characters.
1const person = {2name: 'Alice',3age: 30,4city: 'New York'5};67console.log(person['name']); // Output: Alice8console.log(person['age']); // Output: 30
Alice 30
1const person = {2name: 'Alice',3age: 30,4city: 'New York'5};67const propertyName = 'name';8console.log(person[propertyName]); // Output: Alice
| Concept | Description |
|---|---|
| Object Literals | Create objects using {} with key-value pairs. |
| Dot Notation | Access properties using a period . between the object and property name. |
| Bracket Notation | Access properties using square brackets [] with a string expression. |
In the next tutorial, we'll explore JavaScript Object Methods & this. You'll learn how to add functions as methods to objects and understand the behavior of the this keyword within these methods. This will be essential for implementing more complex object-oriented programming concepts in JavaScript.
Stay tuned!