What is object in JS explain with example?

Asked 19-Jul-2021
Viewed 181 times

1 Answer


1

Javascript language is Object-Oriented Programming Langauge. Objects like C++, Java are also created in Javascript. Objects of Javascript have some methods and some properties. If viewed from the point of view of Objects, then every part of JavaScript can be made Object. But when the object is created then the 'new' keyword is used. When Number, Boolean and String are used, the 'new' keyword is used. But Array, Maths, Dates, Functions and Object are already objects.

Objects in Javascript are created in three ways.
  1. Using Object Literal
  2. Using new keyword
  3. Using Object Constructor

By object literal

Syntax:
Object-name = {property1:value1, property2:value2 --- propertyN:valueN } ;
Example:
emp={id:102,name:'Shyam Kumar',salary:40000}  
console.log(emp.id+' '+emp.name+' '+emp.salary);

By creating instance of object directly (using new keyword)

Syntax:
 var objectname=new Object();  
Example:
var emp=new Object();  
emp.id=101;  
emp.name='Ravi Malik';  
emp.salary=50000;  
console.log(emp.id+' '+emp.name+' '+emp.salary);  

By using an object constructor (using new keyword)

Syntax:
 function emp(arguments1, arguments2,---){  
 this.property1=argument1;
 this.property2=argument2;
 this.propertyN=argumentN;
 }  
Example:
function emp(id,name,salary){  
this.id=id;  
this.name=name;  
this.salary=salary;  
}  
e=new emp(103,'Vimal Jaiswal',30000);  
console.log(e.id+' '+e.name+' '+e.salary);