JavaScript Objects
Objects are a cornerstone of modern programming, providing a powerful way to represent real-world entities and their behaviors. They are essentially data structures that encapsulate both data (properties) and actions (methods), offering a structured approach to organizing and managing complex information.
JavaScript Objects
Introduction
In JavaScript, objects are fundamental data structures used to represent real-world entities. They are collections of key-value pairs, where keys are strings and values can be any data type.
Methods for Defining JavaScript Objects
There are multiple ways to define JavaScript objects:
Using an Object Literal
The most common way to define an object is using an object literal. It is a simple and concise syntax.
const person = { name: "John Doe", age: 30, occupation: "Software Engineer"};
Do You Know?
Object literals are the most flexible and frequently used method for creating objects.
Using the new Keyword
You can also create an object using the new
keyword and the Object()
constructor.
const car = new Object();car.brand = "Toyota";car.model = "Camry";car.year = 2023;
Using an Object Constructor
You can define a custom constructor function to create objects of a specific type.
function Vehicle(brand, model, year) { this.brand = brand; this.model = model; this.year = year;}const car = new Vehicle("Honda", "Civic", 2022);
Using Object.assign()
The Object.assign()
method allows you to copy properties from one object to another. It is useful for creating new objects based on existing ones.
const user = { name: "Alice" };const newUser = Object.assign({}, user, { age: 25 });
Using Object.create()
The Object.create()
method creates a new object with the specified prototype.
const personPrototype = { greet() { console.log("Hello!"); }};const person = Object.create(personPrototype);person.name = "Bob";
Using Object.fromEntries()
The Object.fromEntries()
method converts an iterable of key-value pairs into an object.
const entries = [["name", "Jane"], ["age", 35]];const user = Object.fromEntries(entries);
Object Constructor Functions
Constructor functions are used to create objects with specific properties and methods. They use the this
keyword to refer to the newly created object.
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();
JavaScript Object Methods
JavaScript objects have several built-in methods that provide functionality to manipulate and access their properties and methods.
General Methods
Object.keys()
The Object.keys()
method returns an array of the object's own enumerable property names.
const person = { name: "Alice", age: 30 };const keys = Object.keys(person);console.log(keys); // Output: [ 'name', 'age' ]
Object.values()
The Object.values()
method returns an array of the object's own enumerable property values.
const person = { name: "Alice", age: 30 };const values = Object.values(person);console.log(values); // Output: [ 'Alice', 30 ]
Property Management Methods
Adding Properties
You can add new properties to an object using the dot notation or the bracket notation.
const person = { name: "Bob" };person.age = 25; // Dot notationperson["occupation"] = "Developer"; // Bracket notation
Updating Properties
To update existing properties, simply assign a new value to them.
const person = { name: "Alice", age: 30 };person.age = 35; // Updating the age property
Deleting Properties
Use the delete
keyword to remove properties from an object.
const person = { name: "Bob", age: 25 };delete person.age;
Object Protection Methods
Object.freeze()
The Object.freeze()
method prevents any further modification of an object. It makes the object immutable.
const person = { name: "Alice", age: 30 };Object.freeze(person);person.age = 35; // This will have no effect
Important Note
Frozen objects are completely immutable, meaning their properties cannot be modified, added, or deleted.
Prototype Inheritance
Adding Properties and Methods to Objects Using Prototype
JavaScript uses prototype inheritance to extend objects with new properties and methods. You can add new properties and methods to the prototype of a constructor function.
function Person(name) { this.name = name;}Person.prototype.greet = function() { console.log("Hello, my name is " + this.name);};const john = new Person("John");john.greet(); // Output: Hello, my name is John
Object Setters and Getters
Setters and getters allow you to control how properties are accessed and modified. They provide a way to encapsulate and validate data.
const person = { _age: 25, get age() { return this._age; }, set age(newAge) { if (newAge > 0) { this._age = newAge; } else { console.error("Age must be a positive number."); } }};console.log(person.age); // Output: 25person.age = 30;console.log(person.age); // Output: 30person.age = -1; // Output: Age must be a positive number.
Summary
- JavaScript objects are key-value pairs used to represent real-world entities.
- Objects can be defined using object literals, the
new
keyword, object constructors, and various methods. - Objects have built-in methods for managing properties, protecting their integrity, and implementing inheritance.
- Setters and getters provide a way to control how properties are accessed and modified.