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

JavascriptObject Oriented ProgrammingFront End Technology

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.

Live Demo

<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.

Live Demo

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

Output

javascript
raja
Published on 30-Jul-2019 12:21:57
Advertisements