Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

JS Objects


What's a JavaScript Object?

The JavaScript Object is a collection of different data.

For example, a person can be described as an Object in JavaScript as per below:

  • Name: John
  • Surname: Smiths
  • Age: 41
  • Hair: black

In JavaScript it would be declared as an Object:

const person = { Name: "John", Surname: "Smiths", age: 41, hair: "black" };

How can I access the Object properties?

You can access the Object Properties in two ways:

1. The first way: objectName.propertyName

               
                
<div id="name"></div>                
<script>
// The object:
const person = {
            Name: "John",
            Surname: "Smiths",
            age: 41,
            hair: "black"
            };

// Access the name
document.getElementById("name").innerText = person.Name;
</script>
                
                
              

The output

Make sure that the script is running after the HTML element if the script is inserted directly on the page (within the script tags).

2. The second way: objectName["propertyName"]

               
                
<div id="surname"></div>                
<script>
// The object:
const person = {
            Name: "John",
            Surname: "Smiths",
            age: 41,
            hair: "black"
            };

// Access the name
document.getElementById("surname").innerText = person["Surname"];
</script>
                
                
              

The output