Object property accessing

# object_name.prop_Name or object_Name[‘prop_Name’]
Isn’t both the access properties same, but then why do only the bracket notation works.

Is it some sort of pre-defined way to access properties in for…in ?

One more thing when we access properties using [ bracket] notation we put property name as String, but over here we have directly included the key name via Variable (objectName[prop])? why so ?

Dot notation only works for properties that exist.

obj = {
  one: 1,
  two: 2,
  three: 3
}
console.log(obj.three)      //  3

console.log(obj.four)       //  undefined

When we are using a variable to access properties then we cannot use dot notation because there are likely no keys that match the variable name. The variable may refer to a property that does exist.

prop = 'three'

console.log(obj[prop])       //  3

Notice there are no quotes? This is important to note. If we use quotes then the variable is no longer a variable, but a string (keys are strings).

console.log(obj['prop'])     //  undefined

console.log(obj['three'])    //  3
1 Like

Thankyou @mtf sir for the quick response i almost got everything

but the I am still confused at this

When we are using a variable to access properties then we cannot use dot notation because there are likely no keys that match the variable name. The variable may refer to a property that does exist.

but in the for…in loop we were told that it goes through the object’s properties doesn’t that make the properties exist already. So why can’t the . dot notation can also go through the variable name and check it’s value as it is being done in the bracket notation?

1 Like

Yes, the properties exist, else we couldn’t access them in the loop. It’s just that the keys all have different names. The variable is just one name, but used to access each key in turn.

for (let prop in obj) {
  console.log(prop, obj[prop]);
}

one 1
two 2
three 3

then sir how is that possible that the variable may refer to something out the object’s area?

It is only attempting to refer to a property that does not exist. JS gives undefined if that is the case. In the for..in loop we won’t run into that problem because the loop is iterating over keys that do exist.

Think of a basket of apples that we need to peel so we can make an apple crisp. There are a finite number of apples, and we cannot peel an apple that is not there. We go through the entire basket (in any order) and peel every apple.

1 Like

@mtf, Thankyou sir, I got it now Thankyou for the explanation

1 Like