Computer >> Computer tutorials >  >> Programming >> Javascript

How to access an object value using variable key in JavaScript?


We know that an object value can be accessed by using a Dot notation or Bracket notation. But we can also access the value using a variable key. Let's look over them in a nutshell.

Using Dot and Bracket Notations

Example

In the following example, object value is accessed using Dot and Bracket notation. Using a bracket notation is nothing but using a string key.

<html>
<body>
<script>
   let me = {
      name: 'javascript'
   };
   document.write(me.name);
   document.write("</br>");
   document.write(me['name']);
</script>
</body>
</html>

Output

javascript
javascript


Using Variable Key

Example

In the following example, instead of Dot and Bracket notations, a variable key is used to access the value of an object.

<html>
<body>
<script>
   let me = {
      name: 'javascript'
   };
   let key = 'name'
   document.write(me[key]);
</script>
</body>
</html>

Output

javascript