JavaScript objects and its internal representation
In real life object is an entity having state and behavior . For example: car, pen, bike, chair, glass, keyboard, monitor etc. In the same way JavaScript also has objects with properties as state and methods as behavior and they are represented in the form of
Creating Objects in JavaScript:
There are 3 ways to create objects.
- By object literal
- By creating instance of Object directly (using new keyword)
- By using an object constructor (using new keyword)
- By object literal:
The syntax of creating object using object literal is given below:
var object={property1:value1,property2:value2...,propertyN:valueN}
Here property and its value are separated by a colon (:) and the properties are separated by comma (,). The properties can be accessed using the dot (.) operator.
Example:
var car={name:"Renault",color:"red"};
console.log(car);//{ name: 'Renault', color: 'red' }
console.log("My car name is "+car.name);//My car name is Renault
console.log("My car color is "+car.color);//My car color is red
2. By creating instance of an object:
The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Example:
var car=new Object();
car.name='Fiat';
car.color='red';
console.log(car);//{ name: 'Fiat', color: 'red' }
3. By using object constructor:
Here, we have to create function with arguments. Each argument value can be assigned in the current object by using this keyword which refers to the current object.
Example:
function car(name,color)
{
this.name=name;
this.color=color;
}
var car1=new car("Fiat","Red");
console.log(car1);//{ name: 'Fiat', color: 'red' }
Accessing object values:
We can access the object values by using dot (.) notation and bracket ([]) notation. If we are using bracket ([]) notation to access object values we have to specify the key as string within quotes (“”).
Example:
var car={name:"Renault",color:"red"};
console.log("Name :"+car.name);//Name :Renault
console.log("Name :"+car["name"]);//Name :Renault
Modifying object values:
We can use the dot (.) notation and bracket ([]) to modify any value in a JSON object.
Example:
var car1={name:"Renault",color:"red"};
var car2={name:"Fiat",color:"blue"};
car1.color="brownish red";
car2["color"]="metallic blue";
console.log(car1);//{ name: 'Renault', color: 'brownish red' }
console.log(car2);//{ name: 'Fiat', color: 'metallic blue' }
Deleting object properties:
Use the delete keyword to delete properties from a JSON object.
Example:
var car={name:"Fiat",color:"red",engine:"Chevy V8"};
delete car.engine;
console.log(car);//{ name: 'Fiat', color: 'red' }