Open In App

JavaScript Property Accessors Method

Property Accessors allow access with the property name or keys of an object (Reading, Creating, Updating).

There are two notations in JavaScript that allows us to access object’s properties:



If the object does not find a matching key(or property name or method name), the property accessors return undefined.

Dot Notation



The property must have a valid JavaScript identifier in the object.property syntax. (The property names are technical ‘IdentifyingNames’ as part of ECMAScript standards, not ‘Identifiers,’ so that words reserved are used but not recommended).

 object_name.property_name;

Example :




<script>
  const obj = {
   g: 'geeks',
   fg: 'forgeeks'
  };
  console.log(obj.g)
</script>

Output :

geeks

Bracket Notation

An expression is a valid code unit that resolves/assesses to a value. The resolution value is then typecasted into a string, which is considered as the propertyName.

Note: Any property_name that is a keyword cannot be accessed, as it is going to give you an Unexpected Token Error.

object_name[expression];

Example :




const obj = {
 g: 'geeks',
 fg: 'forgeeks'
};
console.log(obj['fg'])

Output :

forgeeks

Article Tags :