An object is a collection of key-value pairs, where each key is a string (or symbol) and the corresponding value can be of any type, including other objects.
Objects can be created using the object literal syntax, like this:
const person = {
name: "John",
age: 30,
email: john@example.com
};
In this example, person is an object that has three properties: name, age, and email. The values of these properties are strings and a number, respectively.
Objects can also be created using the new keyword and the Object constructor function, like this:
const person = new Object();
person.name = "John";
person.age = 30;
person.email = "john@example.com";
This creates an empty object using the Object constructor function, and then adds properties to it using dot notation.
In JavaScript, objects are used extensively to represent complex data structures, such as arrays, maps, sets, and more. They are also used to create custom data types and classes, using the prototype-based inheritance model.
Object Properties:
In JavaScript, object properties are the key-value pairs that define the attributes of an object. Objects can have zero or more properties, and each property consists of a name (or key) and a value. The name of a property must be a string or a symbol, and the value can be of any type, including other objects.
There are two ways to access object properties in JavaScript: dot notation and bracket notation.
Dot notation is the most common way to access object properties in JavaScript. It uses the . operator followed by the property name to access the value of the property. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
console.log(person.name); // "John"
console.log(person.age); // 30
console.log(person.email); // "john@example.com"
Bracket notation uses square brackets [] to access object properties. The property name is enclosed in quotes and passed as a string inside the brackets. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
console.log(person['name']); // "John"
console.log(person['age']); // 30
console.log(person['email']); // "john@example.com"
Note that bracket notation is useful when the property name is dynamic and determined at runtime, or when it contains special characters that are not valid in dot notation.
In addition to accessing object properties, JavaScript also provides methods for adding, updating, and deleting object properties, such as Object.assign(), Object.defineProperty(), and the delete operator.
Object Method:
An object method is a function that is defined as a property of an object. Object methods are used to define the behavior of an object and can be called by accessing the method property of the object.
Here’s an example of defining an object method:
const person = {
name: "John",
age: 30,
email: "john@example.com",
sayHello: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
person.sayHello(); // Output: "Hello, my name is John and I am 30 years old."
In this example, sayHello is a method of the person object that logs a message to the console with the person’s name and age.
Object methods can also take parameters like any other function. Here’s an example:
const 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(10, 4)); // Output: 6
In this example, calculator is an object with two methods, add and subtract, that take two parameters and return the result of the corresponding mathematical operation.
Object methods can also access and modify the properties of the object using the this keyword. This allows the method to use and manipulate the object’s data.
const counter = {
count: 0,
increment: function() {
this.count++;
},
decrement: function() {
this.count--;
}
};
console.log(counter.count); // Output: 0
counter.increment();
console.log(counter.count); // Output: 1
counter.decrement();
console.log(counter.count); // Output: 0
In this example, counter is an object with two methods, increment and decrement, that modify the count property of the object.
Object Display:
In JavaScript, there are several ways to display object properties and methods.
One of the simplest ways to display object properties and methods is by using the console.log() method. This method accepts one or more arguments, and displays them in the browser console. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com",
sayHello: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
console.log(person.name); // Output: "John"
console.log(person.age); // Output: 30
console.log(person.email); // Output: "john@example.com"
person.sayHello(); // Output: "Hello, my name is John and I am 30 years old."
Another way to display an object in JavaScript is to convert it to a JSON string using the JSON.stringify() method. This method serializes an object to a JSON-formatted string, which can then be displayed or transmitted to another system. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
const jsonPerson = JSON.stringify(person);
console.log(jsonPerson); // Output: '{"name":"John","age":30,"email":"john@example.com"}'
The Object.keys() method can be used to display the properties of an object as an array of strings. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
const keys = Object.keys(person);
console.log(keys); // Output: ['name', 'age', 'email']
A for…in loop can be used to iterate over the properties of an object and display them. Here’s an example:
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
for (const property in person) {
console.log(`${property}: ${person[property]}`);
}
/* Output:
name: John
age: 30
email: john@example.com
*/
In this example, the for…in loop iterates over the properties of the person object, and logs each property name and value to the console.
Object Accessors:
Object accessors are methods that allow you to get and set the values of an object’s properties. The two types of object accessors are getters and setters.
Getters are methods that allow you to retrieve the value of a property of an object. They are defined using the get keyword followed by the name of the property, and they do not take any arguments. Here’s an example:
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
console.log(person.fullName); // Output: "John Doe"
In this example, the fullName property is defined as a getter method, which returns the concatenated values of the firstName and lastName properties.
Setters are methods that allow you to set the value of a property of an object. They are defined using the set keyword followed by the name of the property, and they take one argument, which is the new value of the property. Here’s an example:
const person = {
firstName: "John",
lastName: "Doe",
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: "Jane"
console.log(person.lastName); // Output: "Smith"
In this example, the fullName property is defined as a setter method, which splits the input string into an array, and sets the values of the firstName and lastName properties.
Object accessors can be useful for data validation and encapsulation. For example, you can use a setter to ensure that a property is always set to a certain data type, or to perform some other kind of validation before setting the value.
Object Constructor:
An object constructor is a function that is used to create objects. Object constructors are defined using the function keyword, and are typically named with a capitalized first letter to indicate that they are constructors.
To create a new object using a constructor, you use the new keyword followed by the constructor function name, and any arguments that the constructor takes. Here’s an example:
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
}
}
const john = new Person("John", "Doe", 30);
console.log(john.getFullName()); // Output: "John Doe"
In this example, we’ve defined an object constructor called Person, which takes three arguments: firstName, lastName, and age. The constructor sets these values as properties of the new object using the this keyword, and defines a getFullName method for the object.
To create a new Person object, we use the new keyword followed by the Person constructor function, passing in the values for the firstName, lastName, and age properties.
Object constructors can be useful when you need to create multiple objects with the same properties and methods. By defining an object constructor, you can create new objects with a consistent structure and behavior.
Object Prototype:
An object’s prototype is a reference to another object that the current object inherits properties and methods from. Every object in JavaScript has a prototype, except for the root object, Object.prototype.
The prototype of an object can be accessed using the Object.getPrototypeOf() method or the __proto__ property. Here’s an example:
const person = {
firstName: "John",
lastName: "Doe",
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
};
const employee = {
jobTitle: "Developer"
};
Object.setPrototypeOf(employee, person);
console.log(employee.getFullName()); // Output: "John Doe"
Object Set:
In JavaScript, the Set object is a built-in data structure that allows you to store unique values of any type, whether primitive values or object references. The Set object is similar to an array, but unlike arrays, Set objects do not allow duplicate values.
Here’s an example of how to create a new Set object:
const mySet = new Set();
To add new values to a Set object, you can use the add() method:
mySet.add(1);
mySet.add("two");
mySet.add({ name: "John", age: 30 });
In this example, we’ve added a number, a string, and an object to the mySet object using the add() method. Note that because Set objects only store unique values, if you try to add a value that is already in the set, it will be ignored.
You can also initialize a Set object with an array of values using the Set() constructor and the spread syntax …:
const myArray = [1, 2, 3, 3, 4, 5];
const mySet = new Set([...myArray]);
In this example, we’ve initialized a Set object with an array of values. Note that the duplicates in the array have been removed, as Set objects only store unique values.
To check if a Set object contains a certain value, you can use the has() method
mySet.has(1); // Output: true
mySet.has(6); // Output: false
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.