What is an object in javascript ?


What is an object in javascript ?

The object is a single entity with various values and methods. A single object can access various values and methods in its scope.

Eg. Object name = car
       Properties = color, price, model, size.
       Methods = start(), drive(), stop(), break().

Here in the above example, the object car has different values, and it can access all the methods in its scope.

How to define object in Javascript

const person {
Firstname: “Ram”,
Lastname: “Kapoor”,
Age: 30,
Education: “Engineering”
};

Here the object person has properties like age, name, education, which we can access using the object person.

We can access the properties using object.property.
Eg. person.age; // this will return the value of age property.

Advantages of using object in javascript

  1. Object encapsulate the data and methods :  Objects encapsulate data and methods, making it easy to operate on data.
  2. Code can get reused :Object help to access any method anywhere, which will help reuse the code.
  3. Can solve any problem very effectively.
  4. Reduce data redundancy:Sometimes, we have to use the same data again and again, so objects help us use the same data again and again without creating any extra variable or object.
  5. Provide better security : Encapsulation in objects provides better data security.

Example No.1:

<html> <body> <h4>Knowledge2life</h4> <p id="demo"></p> <script> const person = {firstName:"Knowledge2", lastName:"life"}; document.getElementById("demo").innerHTML = person.firstName + person.lastName + " learning website."; </script> </body> </html>

OUTPUT:

Knowledge2life

Knowledge2life learning website

Example No.2:

<html> <body> <h4>Knowledge2life</h4> <p id="demo"></p> <script> const person = { firstName: "Online webiste", lastName : "Knowledge2life", id : 5566 }; document.getElementById("demo").innerHTML = person["firstName"] + " " + person["lastName"]; </script> </body> </html>

OUTPUT:

Knowledge2life

Online website Knowledge2life