Table of Contents

    Objects in JavaScript: Understanding OOP Concepts and Examples

    Objects in JavaScript: Understanding OOP Concepts and Examples

    Objects in Javascript

    • An object in JavaScript is an entity with property and type.
    • A property is a variable attached to the object.
    • These properties define the characteristics of the object.
    • For example, car can be an object with properties colormodel, etc.
    • You can access the object's property using dot operator.
    • In this example, car is an object with model as property

    Example

    var car = new Object();
    car.model = 'Ford';
    console.log(car.model);

    Methods to Create Object

    • Create an empty object and then add properties to the object: Example:
    var obj={};
    obj.prop1="Hello";
    obj.prop2="World";
    console.log(obj.prop1 + ' ' + obj.prop2);
    • By using Object Literal ie. Name value pair: Example:
    var student = {Name:"Ben",  age:20};
    console.log(student);
    • By using keyword new Example:
    var obj= new Object();
    obj.prop1="Hello";
    obj.prop2="World";
    console.log(obj.prop1 + ' ' + obj.prop2);

    Nested Objects

    • We can also have an object nested inside another object, i.e., an object will have another object as its property, which in turn has separate properties of its own.
    • Just like the normal objects, these inner objects can also be accessed using dot operator.

    Example:

    var student = { Name:"Ben",  age:20 , degree: {class:"B.Tech",section:"A"}};

    We can access the inner object, class by

    console.log(student.degree.class);