Javascript Objects (key-value pairs, accessing properties, nested objects)
JavaScript objects are a fundamental data structure consisting of key-value pairs.
1. Creating JavaScript Objects
An object can be created using curly braces {}
with keys (properties) and values:
2. Accessing Properties
You can access properties in two ways:
Dot Notation:
object.property
Bracket Notation:
object["property"]
3. Adding and Modifying Properties
You can add or modify properties using dot or bracket notation.
4. Deleting Properties
Use the delete
keyword to remove properties.
5. Nested Objects
Objects can contain other objects as values, creating a nested structure.
Accessing Nested Properties
To access nested properties, chain the dot or bracket notation.
Modifying Nested Properties
You can also modify nested properties similarly.
Optional Chaining
For deeply nested properties, optional chaining (?.
) is helpful if some properties might be undefined
.
6. Looping Through Properties
To loop through an object’s properties, use for...in
or Object.keys()
.
Or using Object.entries()
for both keys and values:
7. Checking Property Existence
Use the in
operator or hasOwnProperty()
.
Mastering these techniques allows for more complex manipulations, especially useful in frameworks like React and data-driven applications.