Introduction to Object In Javascript OOPS

Object:-

An Object is a unique entity which contains property and methods.The characteristics of an Object are called as Property, in Object Oriented Programming and the actions are called methods. An Object is an instance of a class. Objects are everywhere in JavaScript almost every element is an Object whether it is a function,arrays and string. A Method in javascript is a property of an object whose value is a function.
Object can be created in two ways in JavaScript:

  • Using an Object Literal:-

Create a new object in JavaScript by setting its properties inside curly braces. Object literals property values can be any data types, like function literals, arrays, strings, numbers, or boolean.

Let’s create an object with a named book, with properties such as author, published year, title, and a method

Example:-

const book = {
title: “Hippie”,
author: “Paulo Coelho”,
year: “2018”
}

After creating an object you can get the value with dot notation. For example, we can get the value of the title with book.title. We can also access the properties with square brackets: book[‘title’].

  • Using Object Constructor:-

     Object constructor is the same as a regular function. It will be called each time an object is created. We can use them with the new keyword. Object constructor is useful when we want to create multiple objects with the same properties and methods.

  • Example:-

    const book = {
    title: “Hippie”,
    author: “Paulo Coelho”,
    year: “2018”
    }
    const book1 = {
    title: “The Alchemist”,
    author: “Paulo Coelho”,
    year: “1988”,
    }

    If we want to create multiple book objects we have to duplicate the code for each book. We can keep creating books but it’s kind of a pain — the object constructor helps us to reuse the object literal.