In JavaScript, objects are fundamental data structures used to store collections of related data and functionality. They are composed of key-value pairs, where the key is a string (or Symbol) that acts as an identifier for the value associated with it. Objects in JavaScript are versatile and can represent complex data structures, including arrays, functions, and even other objects. Here's an overview of objects in JavaScript along with examples:
Creating Objects:
Object Literal:
// Object Literal const person = { name: 'John', age: 30, greet: function() { console.log('Hello!'); } };
- Using the
new
Keyword: - // Using the new keyword const car = new Object(); car.make = 'Toyota'; car.model = 'Camry';
Accessing Object Properties:
- console.log(person.name); // Output: Johnconsole.log(car['make']); // Output: Toyota
Adding and Modifying Properties:
Deleting Properties:
Object Methods:
Objects can contain functions, known as methods, which can be invoked using dot notation or bracket notation.
person.greet(); // Output: Hello!
Object Constructors and Prototypes:
JavaScript also supports constructor functions and prototypes for creating objects with shared properties and methods.
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { console.log(`Hello, my name is ${this.name}`); }; const john = new Person('John', 30); john.greet(); // Output: Hello, my name is John
Object Destructuring:
Object Iteration:
Object Methods:
Objects have built-in methods like Object.keys()
, Object.values()
, and Object.entries()
for working with object properties.
console.log(Object.keys(person)); // Output: ["name", "greet"] console.log(Object.values(person)); // Output: ["John", 30, ƒ] console.log(Object.entries(person)); // Output: [["name", "John"], ["age", 30], ["greet", ƒ]]
0 Comments