JavaScript objects are fundamental data structures that allow you to store and organize related data and functionality. They are collections of key-value pairs, where each key is a unique identifier for a property or method.
There are multiple ways to create objects in JavaScript. The most common methods are object literals and the constructor function.
Object literals provide a simple and concise way to create objects:
const person = {
name: "John Doe",
age: 30,
greet: function() {
console.log("Hello!");
}
};
Constructor functions allow you to create multiple objects with the same structure:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, I'm " + this.name);
};
}
const john = new Person("John Doe", 30);
You can access object properties using dot notation or bracket notation:
console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation
Methods are functions stored as object properties. They can access and manipulate the object's data:
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
Prototypes allow objects to inherit properties and methods from other objects. This concept is crucial for understanding JavaScript's object-oriented programming model. Learn more about JavaScript Prototypes.
delete
operator to remove properties from objects.Object.keys()
method returns an array of an object's enumerable property names.Object.freeze()
.To deepen your understanding of JavaScript objects, explore these related topics:
By mastering JavaScript objects, you'll be well-equipped to create more complex and organized code structures in your applications.