Some basic Javascript object examples

Saul Goodman May 17, 2019 Loading...

The following basic examples will help you learn Javascript object more easily.

Example 1

A Javascript object is a variable, but it can contain many values.

Create a “index.html” file and add the code below into it:

<html>
<body>
    <script>
        var dog = {
            name: 'Tom',
            age: 1,
            breed: 'Boxer'
        }

        //first method to access object properties
        console.log(dog.name); 

        //second method to access object properties
        console.log(dog['breed']);
    </script>
</body>
</html>

Open the file by Chrome and press F12 > Console to see the output:

Tom
Boxer

Examples 2

You can also create an object like this:

<html>

<body>
    <script>
        var box = new Object();
        box.color = 'Blue';
        box.weight = '1 kg';
        
        console.log(box.color);
        console.log(box.weight);
    </script>
</body>

</html>

Run the code using Chrome and see the output in Console:

Blue
1 kg

Examples 3

A Javascript object can have methods.

<html>

<body>
    <script>
        var mrWhite = {
            name: 'Walter White',
            age: 60,
            job: 'actor',
            birthYear: function(){
                return 2019 - this.age;
            }
        }
        
        // display Mr. White birthyear into the browser console 
        console.log(mrWhite.birthYear());
    </script>
</body>

</html>

Output:

1959

This tutorial ends here!

avatar
Welcome to KINDACODE. Have a nice day and code well!