Introduction to JavaScript Objects In JavaScript, objects are one of the fundamental data types used to store and manipulate data. Objects are collections of key-value pairs, where each value is accessed using its corresponding key. This documentation provides an in-depth understanding of JavaScript objects, their creation, manipulation, and various features.
Creating JavaScript Objects There are multiple ways to create JavaScript objects:
- Object Literal Notation:
javascriptconst person = {
name: 'John Doe',
age: 30,
occupation: 'Developer'
};
- Constructor Function:
javascriptfunction Person(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
const person = new Person('John Doe', 30, 'Developer');
- Object.create():
javascriptconst person = Object.create(null);
person.name = 'John Doe';
person.age = 30;
person.occupation = 'Developer';
Accessing and Modifying Object Properties Object properties can be accessed and modified using dot notation or square bracket notation.
- Dot Notation:
javascriptconsole.log(person.name); // Output: John Doe
person.age = 35;
- Square Bracket Notation:
javascriptconsole.log(person['name']); // Output: John Doe
person['age'] = 35;
Iterating Over Object Properties
To iterate over object properties, you can use the for...in
loop:
javascriptfor (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Checking Object Properties
To check if an object has a specific property, you can use the hasOwnProperty()
method:
javascriptconsole.log(person.hasOwnProperty('name')); // Output: true
console.log(person.hasOwnProperty('address')); // Output: false
Object Methods Objects can also have methods, which are functions stored as object properties.
javascriptconst calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(5, 3)); // Output: 2
Object Prototypes and Inheritance JavaScript objects can inherit properties and methods from other objects using prototypes.
javascriptfunction Animal(name) {
this.name = name;
}
Animal.prototype.sayHello = function() {
console.log(`Hello, I'm ${this.name}`);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log('Woof woof!');
};
const dog = new Dog('Max', 'Labrador');
dog.sayHello(); // Output: Hello, I'm Max
dog.bark(); // Output: Woof woof!
This documentation provides a brief overview of JavaScript objects, their creation, manipulation, iteration, property checking, methods, and inheritance. Objects are powerful and versatile data structures in JavaScript that play a crucial role in web development.
0 Comments