22
loading...
This website collects cookies to deliver better user experience
expression.identifier
const items = {
food: "soup",
"phone-1": "iphone 12"
}
// to access food property
items.food
// output => soup
items
is an object from which we need to access a property, and food
is an identifier. Accessing food property of items is easy enough. However, if we try to access the phone-1
property through dot notation, it won't work. Wondering why? Because it is not a valid identifier. So, how can we access that property? We'll cover that in the next section.Note: The identifier should be a valid identifier.
expression[expression]
items
and it had two properties. So, to access the food
property, we simply have to do this: items[food]
. Now about that second property, do you think we would be able to access that? phone-1
property by doing this: items["phone-1"]
. When using square brackets, the expression between the brackets is evaluated and converted to a string to get the property name. Whereas using dot notations only fetches the value.const items = {
food: "soup"
"phone-1": "iphone 12"
}
const { food } = items;
food;
// output => soup
food
with the value of property food
.Note: The variable should have the same name as the property.
phone-1
property, we can use aliasing.const { identifier: aliasIdentifier } = expression;
phone-1
property, do this:const {"phone-1": newVariable} = items
newVariable;
// output => iphone 12