How to create an object and access its properties in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code creating an object and accessing its properties in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Hoisting in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="btn">CLICK HERE</button>
<h3>
Click on the above button to create and access a object
</h3>
<script>
   let btnEle = document.querySelector(".btn");
   let resEle = document.querySelector(".result");
   let obj = {
      firstName: "Rohan",
      lastName: "Sharma",
      welcome() {
         return "Welcome " + this.firstName + " " + this.lastName;
      },
   };
   btnEle.addEventListener("click", () => {
      resEle.innerHTML = "obj.firstName = " + obj.firstName + "<br>";
      resEle.innerHTML += "obj.lastName = " + obj.lastName + "<br>";
      resEle.innerHTML += "obj.welcome() = " + obj.welcome() + "<br>";
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 15-Jul-2020 13:17:36
Advertisements