Understanding and working with objects in JavaScript
Objects in JavaScript are complex data types that allow you to store collections of data and functionality together. They are one of the most important concepts in JavaScript.
There are several ways to create objects in JavaScript:
// Object literal notation
const person = {
name: "John",
age: 30,
city: "New York"
};
// Using the Object constructor
const car = new Object();
car.make = "Toyota";
car.model = "Corolla";
car.year = 2020;
You can access object properties using dot notation or bracket notation:
console.log(person.name); // Outputs: John
console.log(car["model"]); // Outputs: Corolla
Objects can also contain functions, which are called methods:
const calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
console.log(calculator.add(5, 3)); // Outputs: 8
You can use constructor functions to create multiple objects of the same type:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
}
}
const john = new Person("John", 30);
john.greet(); // Outputs: Hello, my name is John
The Object.create() method creates a new object, using an existing object as the prototype:
const personProto = {
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
const mary = Object.create(personProto);
mary.name = "Mary";
mary.greet(); // Outputs: Hello, my name is Mary
JavaScript provides several built-in methods for working with objects:
const person = {name: "John", age: 30};
// Object.keys(): Returns an array of a given object's own enumerable property names
console.log(Object.keys(person)); // Outputs: ["name", "age"]
// Object.values(): Returns an array of a given object's own enumerable property values
console.log(Object.values(person)); // Outputs: ["John", 30]
// Object.entries(): Returns an array of a given object's own enumerable string-keyed property [key, value] pairs
console.log(Object.entries(person)); // Outputs: [["name", "John"], ["age", 30]]
These are just a few examples of working with objects in JavaScript. Objects are a fundamental part of the language and are used extensively in JavaScript programming.