Javascript Object Properties
Objects are collections of key-value pairs, where the key is a string (or symbol in ES6+) and the value can be of any data type.
As an example:
const person = {
name: "John",
age: 30,
};
Accessing JavaScript Properties
You can access object properties using dot notation or bracket notation.
As an example:
// Using dot notation to access object properties
const person = {
name: "John",
age: 30,
};
console.log(person.name); // Output: 'John'
console.log(person.age); // Output: 30
In the example:
- We use dot notation to access the
name
andage
properties of theperson
object.
// Using bracket notation to access object properties
console.log(person["name"]); // Output: 'John'
console.log(person["age"]); // Output: 30
In the example:
- We use bracket notation to access the
name
andage
properties of theperson
object. - Note that when using bracket notation, the property name must be enclosed in quotes (single or double).
You can also use a variable as the property name when using bracket notation:
const propertyName = "name";
console.log(person[propertyName]); // Output: 'John'
In the example:
- We use the
propertyName
variable to access thename
property of theperson
object.
If you try to access a property that does not exist using dot notation, you will get undefined
:
console.log(person.address); // Output: undefined
Note that in both cases, trying to access a property that does not exist will not throw an error. If you want to check if a property exists in an object before trying to access it, you can use the in
operator
For example:
console.log("name" in person); // Output: true
console.log("address" in person); // Output: false
In the example:
- We use the
in
operator to check if theperson
object has aname
property (which it does), and if it has an address property (which it does not).
JavaScript for...in
Loop
The for...in
loop is used to iterate over the properties of an object. Here's an example:
const person = {
name: "John",
age: 30,
occupation: "engineer",
};
for (const property in person) {
console.log(`${property}: ${person[property]}`);
}
In the example:
- We use a
for...in
loop to iterate over the properties of theperson
object. - The loop iterates over each property of the object and assigns the property name to the
property
variable. - We then use bracket notation to access the value of each property using the
property
variable.
The output of the above code will be:
name: John;
age: 30;
occupation: engineer;
Note that the order of iteration is not guaranteed, so the properties may not be logged in the order in which they were defined in the object.
You can also use the hasOwnProperty()
method to check if a property belongs to the object itself or to its prototype chain.
As an example:
const person = {
name: "John",
age: 30,
occupation: "engineer",
};
for (const property in person) {
if (person.hasOwnProperty(property)) {
console.log(`${property}: ${person[property]}`);
}
}
In the example:
- We add an
if
statement inside the loop to check if the property belongs to theperson
object itself (as opposed to its prototype chain). - The
hasOwnProperty()
method returnstrue
if the property belongs to the object itself andfalse
if it belongs to the prototype chain. - By adding this check, we ensure that only the properties of the
person
object itself are logged.
The output of the above code will be the same as before:
name: John;
age: 30;
occupation: engineer;
Adding New Properties
You can add new properties to an object using either dot notation or bracket notation.
As an example:
// Adding a new property using dot notation
const person = {
name: "John",
age: 30,
};
person.occupation = "engineer";
console.log(person); // Output: {name: 'John', age: 30, occupation: 'engineer'}
In the example:
- We add a new
occupation
property to theperson
object using dot notation. - We simply specify the new property name and assign it a value.
// Adding a new property using bracket notation
const person = {
name: "John",
age: 30,
};
person["occupation"] = "engineer";
console.log(person); // Output: {name: 'John', age: 30, occupation: 'engineer'}
In the example:
- We add a new
occupation
property to theperson
object using bracket notation. - We enclose the new property name in quotes and use bracket notation to assign it a value.
You can also use a variable as the property name when using bracket notation:
const propertyName = "occupation";
person[propertyName] = "engineer";
console.log(person); // Output: {name: 'John', age: 30, occupation: 'engineer'}
In the example:
- We use the
propertyName
variable to add a new occupation property to theperson
object using bracket notation.
If you try to add a property that already exists, its value will be overwritten:
person.age = 40;
console.log(person); // Output: {name: 'John', age: 40, occupation: 'engineer'}
In the example:
- We change the value of the
age
property of theperson
object from30
to40
.
You can also add multiple properties to an object at once using the Object.assign()
method. Here's an example:
const person = {
name: "John",
age: 30,
};
const additionalInfo = {
occupation: "engineer",
address: "123 Main St",
};
Object.assign(person, additionalInfo);
console.log(person); // Output: {name: 'John', age: 30, occupation: 'engineer', address: '123 Main St'}
In the example:
- We use the
Object.assign()
method to add the properties from theadditionalInfo
object to theperson
object. - The first argument to
Object.assign()
is the target object (in this case,person
), and the subsequent arguments are the source objects (in this case,additionalInfo
). - The method copies the properties from the source objects to the target object, overwriting any existing properties with the same name.
Deleting Properties
You can delete properties from an object using the delete
keyword.
As an example:
const person = {
name: "John",
age: 30,
occupation: "engineer",
};
delete person.age;
console.log(person); // Output: {name: 'John', occupation: 'engineer'}
In the example:
- We use the
delete
keyword todelete
theage
property from theperson
object. - When we log the
person
object to the console, we can see that theage
property is no longer present.
Note that if you try to access a property that has been deleted, you will get undefined
:
console.log(person.age); // Output: undefined
You can also use a variable as the property name when deleting a property:
const propertyName = "occupation";
delete person[propertyName];
console.log(person); // Output: {name: 'John'}
In the example:
- We use the
propertyName
variable to delete theoccupation
property from theperson
object.
If you try to delete a property that does not exist, nothing happens and no error is thrown:
delete person.address;
console.log(person); // Output: {name: 'John'}
In the example:
- We try to delete the
address
property from theperson
object, but since this property does not exist, nothing happens.
Nested Objects
You can create nested objects, which are objects that have properties that are also objects.
As an example:
const person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
},
};
console.log(person.address.street); // Output: '123 Main St'
In this example:
The person
object has a property called address
, which is itself an object with properties street
, city
, and state
.
- We access the street property of the address object using dot notation and log it to the console.
You can also create nested objects using bracket notation:
const person = {
name: "John",
age: 30,
"address info": {
street: "123 Main St",
city: "Anytown",
state: "CA",
},
};
console.log(person["address info"]["street"]); // Output: '123 Main St'
In the example:
- The
person
object has a property called'address info',
which is itself an object with properties street, city, and state. - We access the street property of the
'address info'
object using bracket notation and log it to the console.
You can also use a combination of dot notation and bracket notation to access nested properties:
console.log(person["address"]["state"]); // Output: 'CA'
console.log(person.address["city"]); // Output: 'Anytown'
In the example:
- We access the
state
andcity
properties of theaddress
object using a combination of dot notation and bracket notation.
You can add new properties to nested objects using the same techniques described earlier:
person.address.zipCode = "12345";
console.log(person); // Output: {name: 'John', age: 30, address: {street: '123 Main St', city: 'Anytown', state: 'CA', zipCode: '12345'}}
In the example:
- We add a new
zipCode
property to theaddress
object of theperson
object using dot notation.
Nested Arrays and Objects
You can create nested arrays and objects, which are arrays or objects that contain other arrays or objects.
As an example:
const person = {
name: "John",
age: 30,
addresses: [
{street: "123 Main St", city: "Anytown", state: "CA"},
{street: "456 Oak St", city: "Otherville", state: "NY"},
],
};
console.log(person.addresses[0].street); // Output: '123 Main St'
console.log(person.addresses[1].city); // Output: 'Otherville'
In the example:
- The
person
object has a property calledaddresses
, which is an array containing two objects with propertiesstreet
,city
, andstate
. - We access the
street
property of the first address object using bracket notation and log it to the console. - We also access the
city
property of the second address object using bracket notation and log it to the console.
You can add new elements to nested arrays using the push
method:
person.addresses.push({
street: "789 Elm St",
city: "Another Town",
state: "TX",
});
console.log(person.addresses); // Output: [{ street: '123 Main St', city: 'Anytown', state: 'CA' }, { street: '456 Oak St', city: 'Otherville', state: 'NY' }, { street: '789 Elm St', city: 'Another Town', state: 'TX' }]
In the example:
- We use the
push
method to add a new address object to the end of theaddresses
array of theperson
object.
You can also delete elements from nested arrays using the splice
method:
person.addresses.splice(1, 1);
console.log(person.addresses); // Output: [{ street: '123 Main St', city: 'Anytown', state: 'CA' }, { street: '789 Elm St', city: 'Another Town', state: 'TX' }]