JavaScript(JS) Objects
JavaScript Objects
In JavaScript, an object is a collection of key-value pairs, where each key is a string (or symbol) and each value can be any type of data, including other objects. Objects are one of the fundamental data types in JavaScript and are used extensively throughout the language and the web.
Here's an example of an object in JavaScript:
const person = { name: "John", age: 30, address: { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" } };:ecruoSwww.theitroad.com
In this example, we've defined an object called person
, which has three properties: name
, age
, and address
. The name
and age
properties are simple string and number values, respectively, while the address
property is itself an object with four properties: street
, city
, state
, and zip
.
We can access the properties of an object using either dot notation or bracket notation:
console.log(person.name); // Output: "John" console.log(person["age"]); // Output: 30 console.log(person.address.city); // Output: "Anytown"
In the first example, we're using dot notation to access the name
property of the person
object. In the second example, we're using bracket notation to access the age
property. And in the third example, we're using dot notation to access the city
property of the nested address
object.
We can also add, update, and delete properties of an object dynamically:
person.email = "[email protected]"; // Add a new property person.age = 31; // Update an existing property delete person.address; // Delete a property
In this example, we're adding a new property called email
to the person
object, updating the value of the age
property, and deleting the address
property.
Objects are a powerful and flexible data type in JavaScript, and are used extensively in web development, particularly in client-side scripting and data storage.
JavaScript Object Declaration
In JavaScript, there are several ways to declare and create objects. Here are a few examples:
- Object Literal Notation:
const person = { name: "John", age: 30, address: { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" } };
In this method, we define an object using curly braces {}
and list the properties and their values separated by commas.
- Object Constructor Function:
function Person(name, age, address) { this.name = name; this.age = age; this.address = address; } const person = new Person("John", 30, { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" });
In this method, we define a constructor function Person
that takes parameters for the properties of the object, and uses the this
keyword to assign those values to properties of the new object created using the new
keyword.
- Object.create method:
const personPrototype = { name: "", age: 0, address: {} }; const person = Object.create(personPrototype); person.name = "John"; person.age = 30; person.address = { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" };
In this method, we define an object personPrototype
that serves as a prototype for the new object we want to create. We then use the Object.create
method to create a new object based on personPrototype
. We can then set the properties of this new object directly.
These are just a few examples of ways to create objects in JavaScript. The choice of method will depend on the specific use case and requirements of the project.
JavaScript Object Properties
In JavaScript, object properties are key-value pairs that define the characteristics and behavior of an object. Here are some important things to know about object properties:
Property names: In JavaScript, object property names are always strings (or symbols, in some cases). They can be defined using dot notation (
obj.prop
) or bracket notation (obj["prop"]
). Note that if you use bracket notation, you can use a variable to dynamically set the property name.Property values: The values of object properties can be any JavaScript data type, including numbers, strings, booleans, arrays, functions, and even other objects.
Property attributes: Object properties can also have attributes that define additional characteristics and behavior. Some common attributes include:
- Writable: Specifies whether the value of the property can be changed.
- Enumerable: Specifies whether the property is included when the object is enumerated (for example, in a
for...in
loop). - Configurable: Specifies whether the property can be deleted or its attributes changed.
You can define these attributes using the Object.defineProperty
method or the Object.defineProperties
method.
Here's an example of defining an object property using Object.defineProperty
:
const obj = {}; Object.defineProperty(obj, "prop", { value: 42, writable: false, enumerable: true, configurable: false }); console.log(obj.prop); // Output: 42 obj.prop = 43; // Error: Cannot assign to read only property 'prop' delete obj.prop; // Error: Cannot delete property 'prop'
In this example, we're defining a new property called prop
on an empty object obj
. We're setting the initial value of the property to 42
, making it read-only (writable: false
), enumerable (enumerable: true
), and non-configurable (configurable: false
). This means that we can read the value of the property (console.log(obj.prop)
), but we can't change it (obj.prop = 43
) or delete it (delete obj.prop
).
Understanding object properties is an essential part of working with objects in JavaScript.
Accessing Object Properties
In JavaScript, there are two main ways to access object properties: dot notation and bracket notation.
- Dot Notation: This is the most common way to access object properties. You use a dot followed by the property name to access its value. Here's an example:
const person = { firstName: "John", lastName: "Doe", age: 30 }; console.log(person.firstName); // Output: "John" console.log(person.age); // Output: 30
In this example, we're accessing the firstName
and age
properties of the person
object using dot notation.
- Bracket Notation: This method is used when the property name contains spaces or special characters or is a dynamic value that is not known until runtime. In this case, you use brackets
[ ]
and pass in the property name as a string. Here's an example:
const person = { "first name": "John", "last name": "Doe", age: 30 }; console.log(person["first name"]); // Output: "John" console.log(person["age"]); // Output: 30
In this example, we're accessing the "first name"
and "age"
properties of the person
object using bracket notation.
Note that you can also use variables to access object properties using bracket notation. Here's an example:
const person = { firstName: "John", lastName: "Doe", age: 30 }; const prop = "firstName"; console.log(person[prop]); // Output: "John"
In this example, we're using a variable prop
to access the firstName
property of the person
object using bracket notation.
In summary, accessing object properties is an essential part of working with objects in JavaScript, and understanding dot notation and bracket notation is key to manipulating objects effectively.
JavaScript Nested Objects
In JavaScript, it's possible to create nested objects, which are objects that contain other objects as properties. This can be a powerful way to organize and structure data. Here's an example:
const person = { name: { first: "John", last: "Doe" }, age: 30, address: { street: "123 Main St", city: "Anytown", state: "CA", zip: "12345" } };
In this example, we've created a person
object with three properties: name
, age
, and address
. The name
property is itself an object with two properties, first
and last
. The address
property is also an object with four properties, street
, city
, state
, and zip
.
To access a nested object property, you can use dot notation or bracket notation for each level of the nested object. Here are some examples:
console.log(person.name.first); // Output: "John" console.log(person.address.city); // Output: "Anytown" console.log(person["name"]["last"]); // Output: "Doe"
In the first example, we're accessing the first
property of the name
object using dot notation. In the second example, we're accessing the city
property of the address
object using dot notation. In the third example, we're accessing the last
property of the name
object using bracket notation.
You can also modify or add properties to a nested object using the same dot or bracket notation syntax. Here's an example:
person.name.middle = "Edward"; person.address.country = "USA"; console.log(person.name.middle); // Output: "Edward" console.log(person.address.country); // Output: "USA"
In this example, we're adding a new middle
property to the name
object and a new country
property to the address
object using dot notation. We can then access these new properties using the same notation.
JavaScript Object Methods
In JavaScript, objects can also contain methods, which are functions that are associated with the object. Methods can be used to perform operations on the object's data, or to provide functionality related to the object's purpose. Here's an example of an object with a method:
const person = { firstName: "John", lastName: "Doe", age: 30, fullName: function() { return `${this.firstName} ${this.lastName}`; } };
In this example, we've added a fullName
method to the person
object. The method is a function that returns the person's full name by concatenating the firstName
and lastName
properties using string interpolation. Note that within the method, we use the this
keyword to refer to the object itself.
To call the method on the object, we can use dot notation like this:
console.log(person.fullName()); // Output: "John Doe"
In addition to custom methods like fullName
, objects in JavaScript also have built-in methods that can be used to manipulate or access the object's data. Here are a few examples:
Object.keys(obj)
: Returns an array of the object's keysObject.values(obj)
: Returns an array of the object's valuesObject.entries(obj)
: Returns an array of arrays, where each inner array contains a key-value pair
Here's an example of using these built-in methods on an object:
const person = { firstName: "John", lastName: "Doe", age: 30 }; console.log(Object.keys(person)); // Output: ["firstName", "lastName", "age"] console.log(Object.values(person)); // Output: ["John", "Doe", 30] console.log(Object.entries(person)); // Output: [["firstName", "John"], ["lastName", "Doe"], ["age", 30]]
In this example, we're using Object.keys
, Object.values
, and Object.entries
to get different views of the person
object's data.