JavaScript Objects

 JavaScript Objects

We are aware of the primitive data types(PDT) in JavaScript. Except objects, all of the other data types are designed to hold single type of value. Such as integer value, string value, Boolean value etc. 

However, objects are designed to hold different data types. In other words, we can combine and hold different PDTs. 

These have key:value pairs which are called properties. Thus these are similar to arrays. You might want to revisit that lesson to know the difference between arrays and objects. 

Using objects, you can represent a real world object such as a dog, cat, car etc.

Let's look at an example. Here, we created a object literal car. It contains make, color, gps, and wheels as properties. 

You can access the property value using objectName["propertyName"]. Here we are accessing the color of the car using car.color and printing it to screen. 

<!DOCTYPE html>
<html>
<body>
<p id="result"></p>
    <script>
        var car = {
       make: "Merc",
       color: "Silver",
       gps: true,
       wheels: 4
     };
     document.getElementById("result").innerHTML = (car.color);
     </script>

</body>
</html>







Post a Comment

0 Comments

React