JavaScript objects are collections of key-value pairs. They are fundamental to JavaScript programming.
// Example of a JavaScript object
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
1. Object Properties:
Object properties are the values associated with a JavaScript object.
// Accessing object properties
console.log(person.firstName); // Output: John
console.log(person.age); // Output: 30
2. Object Methods:
Object methods are functions stored as object properties.
// Calling object methods
console.log(person.fullName()); // Output: John Doe
3. Display Objects:
You can display objects using console.log()
or by rendering them in the DOM.
console.log(person); // Output: {firstName: "John", lastName: "Doe", age: 30, fullName: ƒ}
4. Object Accessors:
Accessor properties are methods that get or set the value of an object.
// Example of getter and setter
const obj = {
get prop() {
return this._prop;
},
set prop(value) {
this._prop = value;
}
};
obj.prop = 123;
console.log(obj.prop); // Output: 123
5. Object Constructors:
Constructors are functions used for creating objects.
// Example of object constructor
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person1 = new Person("Jane", "Doe");
console.log(person1.firstName); // Output: Jane
6. Object Prototypes:
Prototypes are mechanisms by which JavaScript objects inherit features from one another.
// Adding a method to the prototype
Person.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
console.log(person1.fullName()); // Output: Jane Doe
7. JavaScript Iterables:
Iterables are objects that implement the iterable protocol, meaning they define their iteration behavior.
// Example of iterable
const iterable = {
[Symbol.iterator]() {
let step = 0;
return {
next() {
step++;
if (step === 1) {
return { value: 'This', done: false };
} else if (step === 2) {
return { value: 'is', done: false };
} else if (step === 3) {
return { value: 'an', done: false };
} else if (step === 4) {
return { value: 'iterable.', done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (const value of iterable) {
console.log(value);
}
8. JavaScript Sets:
Sets are collections of unique values.
// Example of a set
const set = new Set([1, 2, 3, 4, 4, 4]);
console.log(set); // Output: Set(4) {1, 2, 3, 4}
9. JavaScript Maps:
Maps are collections of key-value pairs with unique keys.
// Example of a map
const map = new Map();
map.set('key1', 'value1');
map.set('key2', 'value2');
console.log(map.get('key1')); // Output: value1