-1

Below is a simple Object I created in Javascript.

var obb = {name : "Charlie", Age : 28 , Location : "London" , Job : "Detective"} ;

var x = "name";
console.log(obb.name);
console.log(obb.x) ;            //Dot notation :- returns value undefined
console.log(obb[x]);            // Square bracket :-  returns correct answer  

I know that there are two methods to fetch values of objects i.e dot notation and square bracket.Now if I am storing value of property in a variable & using dot notation with the variable to fetch value , why is it not working ?

  • If `obb.name` accesses the `name` property, why would `obb.x` access anything but the property `x`? – deceze Dec 04 '22 at 15:28
  • _“I know that there are two methods to fetch values of objects i.e dot notation and square bracket. […] using dot notation with the variable to fetch value, why is it not working?”_ — So you know that there’s dot notation and bracket notation, but you don’t know what the difference is? The [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_Accessors) explains this in great detail. – Sebastian Simon Dec 04 '22 at 15:30
  • 1
    Dot notation only supports literal property names. It can't support variables because then there would be no way for the JS interpreter to know if `obb.x` refers to the property named `x` or a property specified by the variable `x`. For this reason, it unambiguously refers to the property `x` and nothing else. – Lennholm Dec 04 '22 at 15:41

1 Answers1

1

In JavaScript, the object attributes can be accessed using either the dot notation or the bracket notation. Dot notation is frequently used because it is simpler to read and understand. What is the significance of bracket notation and why should we use it? The square bracket syntax [] turns the expression within to a string, allowing us to access object properties via variables.