Header Ads Widget

JavaScript object

In this post, we will discuss about the JavaScript object declaration , their usage , methods, properties and nested objects.

What is object in JavaScript?

In JavaScript object is one of the non-primitive data type, a value container like variable but it can store multiple values. Object stores its property value in "name: value" pair. 

The real life example of object is person, car, cycle, bike, pen, washing machine, etc …

All objects have its properties and values. Let’s understand with real life example.

In washing machine company_name, color, model, weight_capacity are its properties and samsung, black, WA65A4002VS, 6.5 kg are washing machine properties values respectively. The values are different form one machine to another. start(), stop(), resume(), etc.. are the methods of washing machine.

Example of washing machine 

let washing_machine={
company_name:samsung,
color:black,model:WA65A4002VS,
weight_capacity:6.5 kg};

Is everything in JavaScript is object in JavaScript?

Yes, in JavaScript everything is object except primitive values. The primitive values are immutable and does not have properties and methods. The null, undefined, Boolean, string, number are primitive values.

The non-primitive values like functions, arrays, dates, Maths, regular expressions are objects.

How to create/declare object in JavaScript?

You can declare or create an object by three ways.

1. By object literals
2. By instance of object (using new keyword)
3. By object constructor function

By object literals

Syntax

variable object_name={
property_name1: value 1, 
property_name2: value 2
………}

You can define multiple properties and values.

Example:

<script>
let emp={
Id:1002022,
Emp_name:"Rivan boze",
Age:29,
Designation:"Junior Web developer",
Salary:20000};
</script>

In example object of employee is created and Id:1002022, Emp_name:”Rivan boze”, Age:29, Designation:"Junior Web developer", Salary:20000 are properties and values respectively.

Before moving on second method let’s know about accessing object property.

How to access object property?

In above example you can not show the property’s value in output because property of object is not accessed here.

You can access object property using two ways:

1. Using dot (.) notation

Syntax

object.property_name;

To access object property specify object name followed by dot notation and property name that you want to access.

Example of employee object
Displaying the data of employee.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Employee Record</h3>
<script>
//object literals
let emp={
id:1002022,
emp_name:"Rivan boze",
age:29,
designation:"Junior Web developer",
salary:"20000"};
document.write("Employee Id="+emp.id,"<br>","Employee name="+emp.emp_name,"<br>","Age="+emp.age,"<br>","Designation="+emp.designation,"<br>","Salary="+emp.salary
);
</script>
</body>
</html>


2. Using square brackets

Syntax

object[property_name];

The second way to access object property using square brackets also called array notation. Specifying property name in to the square brackets with quotes.

Same example but different accessing method


document.write("Employee Id="+emp["id"],"<br>","Employee name="+emp["emp_name"],"<br>","Age="+emp["age"],"<br>","Designation="+emp["designation"],"<br>","Salary="+emp["salary"]
);

Output ( employee object)
Javascript object (using object literal)
Javascript object using object literal

By instance of object

Syntax

variable object_name=new Object ();

Using new keyword instance of object created object of student directly.

Example

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Student Record</h3>
<script>
//instance of objects
let student=new Object();
student.roll_no=11;
student.name=Trinay khare;
student.standard=6;
student.grade=B;
document.write(Roll no=+student["roll_no"],<br>,Name=+student["name"],<br>,standard=+student["standard"],<br>,Grade=+student["grade"]);
</script>
</body>
</html>

Output:- (student object)
Javascript object using instance of object
Instance of object

Remember: Use '=' sign instead of ':'. Other wise it will generate an error.

By object constructor function

Using above two declaration method only one object had been created. But using constructor function multiple objects can be created with help of this keyword.

You can define function with or without parameters.

Example 1:

Constructor function is defined with parameter.
In example two objects of mobile created. property value has been passed at the time of object declaration.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<script>
//constructor function
function mobile(company_nm,color,ram,camara)
{
this.company_nm=company_nm;
this.color=color;
this.ram=ram;
this.camara=camara;
}
//object creation
mob=new mobile("motog10","Blue","4 GB","48MP");
mobi=new mobile("samsung","Silver","2 GB","16Mp");
//access object properties
document.write("This is ",mob.company_nm," mobile "," with ",mob.ram," RAM <br>");
document.write("This is ",mobi.company_nm," mobile "," with ",mobi.ram," RAM");
</script>
</body>
</html>

Output:-(constructor function)
Javascript object using constructor function
Constructor function with parameter

In output two different objects's different values is displayed.

Example 2:

Constructor function is defined without any parameter.

In second example function have not specify parameter. You can not passed values at time of object declaration.


<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<script>
//constructor function
function mobile()
{
this.company_nm="motog10";
this.color="blue";
this.ram="4 GB";
this.camara="48MP";
}
//object declaration
mob=new mobile();
mob2=new mobile();
//accessing object prpetties
document.write("This is ",mob.company_nm," with ",mob.ram," RAM<br>");
document.write("This is ",mob2.company_nm," with ",mob2.ram," RAM");
</script>
</body>
</html>

Output:(constructor function without parameter)
In output it will display same values. 
Javascript object (constructor function)
Javascript object constructor function

 this” in constructor function 

In constructor function “this” keyword refers to an object. Actually “this” does not have any value, but each argument’s value assigned to the object using ‘this’ keyword. When object is created its value is accessed by ‘function object.proerty name' directly. 

How to add property to object?

You can also add new property to current object. Adding property to current object is very simple. Specify property name with object using dot (.) then assign value to property.

Syntax

object_name.property_name=value;

Example

1) The percentage property is added in student object.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Student Record</h3>
<script>
let student=new Object();
student.roll_no=11;
student.name="Trinay khare";
student.standard=6;
student.grade="B";
document.write("Roll no="+student["roll_no"],"<br>","Name="+student["name"],"<br>","standard="+student["standard"],"<br>","Grade="+student["grade"]);
//Adding percentage property
student.percentage=67;
document.write("<br>",student.name," got ",student.percentage," percentage.");
</script>
</body>
</html>

Output:- (After addeding percentage property to student object)
Adding object property to current object
Adding object property to student object

2) The bonus property is added to emp object.


<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Employee Record</h3>
<script>
let emp={
id:1002022,
emp_name:"Rivan boze",
age:29,
designation:"Junior Web developer",
salary:"20000"};
document.write("Employee Id="+emp.id,"<br>","Employee name="+emp.emp_name,"<br>","Age="+emp.age,"<br>","Designation="+emp.designation,"<br>","Salary="+emp.salary);
//Adding bonus property
emp.bonus=2000;
document.write("<br> The bonus amount is ",emp.bonus);
</script>
</body>
</html>

Output:- (After adding bonus property to emp object)
Adding property to current emp object
Adding property to emp object

How to delete object property?

Like insertion of object property, you can also delete property using delete keyword.

Syntax

delete object_name.property_name;
OR
delete object_name[property_name];

Example

The bonus property is deleted in emp object. After deletion when this property being accessed “undefined” message will display in output.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Employee Record</h3>
<script>
let emp={
id:1002022,
emp_name:"Rivan boze",
age:29,
designation:"Junior Web developer",
salary:"20000"};
document.write("Employee Id="+emp.id,"<br>","Employee name="+emp.emp_name,"<br>","Age="+emp.age,"<br>","Designation="+emp.designation,"<br>","Salary="+emp.salary);
//Adding bonus property
emp.bonus=2000;
document.write("<br> The bonus amount is ",emp.bonus);
//deleting bonus property
delete emp.bonus;
document.write("<br> The bonus amount after deleting bonus property is ",emp.bonus);
</script>
</body>
</html>

Output:-(After deleting bonus property)
Deleting property to emp object
Deleting emp object property

The delete keyword completely remove property from object.

Nested object in JavaScript

Defining one object into another object is called nested object.
The nested object is declare like a object property with curly brackets.

Syntax of declaring nested object



variable object_name=
{
property_name1: value,
property_name2: value,
..
object/property_name:{
property_name1: value,
property_name2: value,
..}
}

Inner object becomes the property of outer object.

Syntax of accessing nested object


Using dot notation (.)


outer_object.inner_object.inner_object_property_name;

Using square brackets []


outer_object.[inner_object].[inner_object_property_name];

You can also used both togather.

outer_object.inner_object.[inner_object_property_name];

Example
The parents object contains the values of children property.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Nested object</h3>
<script>
//nested object
let parents={
mother:"Arti Mishra",
father:"Ashok Mishra",
childrens:{
boy:"shiv",
girl:"krishna",}
};
document.write(parents.childrens.boy," and ",parents.childrens.girl," are children of ",parents.mother," and ",parents.father);
</script>
</body>
</html>

Output:-
Nested object in JavaScript
Nested object in JavaScript

Object method in JavaScript

JavaScript object method is a property of an object that contains function as a value.

Syntax


variable object_name={
property_name1: value,
property_name2: value,
..
property/object_name: function ()
 {
//statement to be executed.
..
}
}

Accessing object method

Syntax


object_name.object_method();

You can access object method by specifying object name followed by dot notation and then specify object method with small brackets and semicolon.

Example
This example calculate the sum of three numbers using object method.


<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Object method</h3>
<script>
//object method
let add={
x:34,
y:56,
z:67,
calculate:function()
{
document.write("sum of three numbers= ",this.x+this.y+this.z);
}
};
document.write("x=",add.x,"<br>","y=",add.y,"<br>","z=",add.z,"<br>");
//accessing object method 
add.calculate();
</script>
</body>
</html>

The three numbers 34, 56 and 67 are assigned to x, y and z properties respectively. The calculate property is turned to the method of add object. In function sum of three numbers are calculated.

Output:-
Object method in JavaScript
Object method

How to add object method to object?

Like property object method can also added after the object is declared.

Syntax

object_name.object_method=function () {
//javascript statement
}

Example

In previous add object the new method multiply is added.

<!DOCTYPE html>
<html>
<head>
<title>object in javascript</title>
</head>
<body>
<h3>Object method</h3>
<script>
//object method
let add={
x:34,
y:56,
z:67,
calculate:function()
{
document.write("sum of three numbers= ",this.x+this.y+this.z);
}
};
document.write("x=",add.x,"<br>","y=",add.y,"<br>","z=",add.z,"<br>");
//adding object method
add.multiply=function()
{
document.write("<br>Multiplication of numbers:-",this.x*this.y*this.z);
};
//accessing object method 
add.calculate();
add.multiply();
</script>
</body>
</html>

Output:-(adding multiply () method)
Adding object method to existing object
Adding new method multiply 

Summary

In this post we had seen about JavaScript object basic. The property is the main part of object declaration. An object contains one or more properties.
You can insert, delete or modify properties not object.
You can not access property without object name.
For simplicity always declare object using object literal.

Post a Comment

0 Comments