JavaScript Objects

in STEMGeeks2 years ago


image.png

Image Source

Objects in JavaScript are collections of properties and values that can be accessed using a name. Everything in JS is object including Date, Array, String and so on. They are used to create a complex data type. For example consider an object bike. Each bike can have different properties like their brand, model, price, mileage. Each properties have their own value. Apart from this bike can have methods like start, stop, set mileage and so on. JavaScript provides three ways to create your object and in this post we will discuss about the first way of creating an object.

The first way is through object-literal. It is perhaps the most easiest way of creating an object and understandable as well. Its a name-value pair list separated by comma inside a curly braces. A simple example is as below:

<script>
    var Bike = {
        Brand: "Apache",
        Model: "RTR 200",
        Price: 350000,
        Mileage: "40 km/l",
        Speed: "127 km/hr"
    }
</script>

If you type console.log(typeof(Bike)); and see in your browser console, you will get the output as "object".

image.png

Inorder to access the properties of the object you can use dot followed by the name of object. For example if you want to know the mileage of your bike then just write console.log(Bike.Mileage);.

image.png

You can also create a method for your object. Lets create one for bike to start it.

<script>
    var Bike = {
        Brand: "Apache",
        Model: "RTR 200",
        Price: 350000,
        Mileage: "40 km/l",
        Speed: "127 km/hr",

        run: function()
        {
            return "The bike is now running.";
        }
    }
</script>

Let's write console.log(Bike.run()); and see in the browser to see if bike is actually starting.

image.png