There are three ways to access JavaScript properties −
- Using dot property access: object.property
- Using square brackets notation: object[‘property’]
- Using object destructuring: let {property} = object
Following is the code for accessing JavaScript object properties −
Example
<!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, .sample { font-size: 18px; font-weight: 500; color: blueviolet; } .sample { color: red; } </style> </head> <body> <h1>Access JavaScript object properties</h1> <div><pre class="sample">{a:22,b:44}</pre></div> <div class="result"></div> <button class="Btn">Access</button> <h3>Click on the above button to access object properites</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let obj = { a: 22, b: 44 }; BtnEle.addEventListener("click", () => { resEle.innerHTML += "obj.a = " + obj.a + "<br>"; resEle.innerHTML += "obj['a'] = " + obj["a"] + "<br>"; let { a } = obj; resEle.innerHTML += "{a}=obj = " + a + "<br>"; }); </script> </body> </html>
Output
On clicking the ‘Access’ button −