DEV Community

Sivakumar Mathiyalagan
Sivakumar Mathiyalagan

Posted on

Objects in Javascript

Object is one of the most important datatype in javascript(as Js is an object oriented programming).It is a non-primitive datatype.

object has properties and behaviour. property are variables that describe the object and behavior are methods that perform some activity or tasks

for example : consider object called student

const Student = {
name: "xyz",
roll: 123,
age: **,

  marks: function(sub1,sub2,sub3){
   return sub1+sub2+sub3;
   }
Enter fullscreen mode Exit fullscreen mode

};

In this syntax,
name,roll,age are properties of student and marks is a function that
calculate the total marks the student acquired in exams.

To print the properties,
console.log(Student.name);
output: xyz.

Student is the object and name is the key through which value is picked and printed in console log

To run the function,
console.log(Student.marks(80,70,90));
output: 240.

in here marks is the key through which the function is called.

Nested object:

which means object inside an object, this is possible as object property may contain one or more nested object inside it to describe its properties and functionality
Enter fullscreen mode Exit fullscreen mode

Example:

const Yamaha = {
founded : 1887,
origin : "Japan",
products : {
bikes : {
name : "XSR",
cc : 155,
fuel : "petrol"
},
pianos:{
name :"ARIUS",
variant: "YDP-165"
}
},
driving: function(){
console.log("driving a vehicle of yamaha");
}
};

In this Yamaha object following are nested objects

  1. bikes
  2. pianos

way to get the values of nested objects
console.log(Yamaha.founded); output = 1887
console.log(Yamaha.products.bikes.name); output = XSR
console.log(Yamaha.products.pianos.variant); output = YDP-165

(TBD) this keyword in object and Object Constructor Functions

referrence:https://www.w3schools.com/js/js_objects.asp

Top comments (0)