Wednesday, March 7, 2018

Javascript Objects Tutorial

Objects

In Javascript object is the main topic to involve and writing more efficient code. So it should be understand clearly before moving into other chapters. Let start....

A object should be created with { .........} with some list of optional properties. Means, Its based Key value pair concepts. A key should be a string and a value can be anything.

Empty Objects :

We can create an empty object by two ways. 

1. By Constructor

2. By empty literal { } (Empty braces).


let user = new Object();
let user = {};  

A simple Object Example:

let test = {     // test is object here
  name: "Raj",  // Key Value pair concept
  age: 19        
};

Here, test is your object which have name and age properties. Raj and 19 is its values.

Add, Read and Remove operation

Adding, Reading and Removing operation is possible at anywhere. So let see one by one.

1. Add Operation

Consider our test object and I need to add one property like "qulaification:Bsc". So the following way we can add,

Syntax:

ObjectName.yourNew Propery = Value;

Example:
test.qulaification="Bsc";

Now just print like console.log(test); It will show below output.

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc" //newly added value updated here     
};

2. Read Operation

By accessing the property of object with dot operator do the read operation.

Syntax:

ObjectName.propertyName;

Example:

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc" //newly added value updated here     
};

alert(test.age); // print 19

3. Remove Operation

By using delete operator we can achieve this. It return true after delete get successful.  Let see the below example.

Syntax:

delete(keyword) objectName.propertyName;

Example:

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc"
};

delete test.age; // Remove age property completely and return true


In next part of this chapter, we are going to see in some cases DOT operator wont work. So how do we achieve that in that scenario. Let see in next post.





No comments:

Post a Comment