Javascript objects
are the collection of key-value
pairs where key
refers to either a string
or symbol
value and value
refers to any Javascript valid data types.
Remember the following points regarding the Javascript object.
var objectName = {
property1 : value1,
property2 : value2,
//...,
propertyN : valueN
};
Source Code
var person = {
name: "Smith",
job: "designer",
salary: 45000,
};
Code Explanation
objectName : It denotes the name of the object.
Object Property Name/Key:It refers to object property name such as property_1, property_2, .....property_n. It will be either string of text or symbols.
Object Property Value:It specifies object property values such as value1, value2,..,valueN.This value will be any valid javascript data types.
Javascript object property can be accesses using two ways:
You can access object property by following ways: objectName.key
Source Code
const person = {
name: "John Doe",
salary: 20000,
};
// accessing property
console.log(person.name); // John
Javascript object property can be accessed by bracket notation.
Source Code
const person = {
name: 'John',
salary: 200000,
};
// accessing property
document.write(person["name"]); // John
Javascript objects can also contain another object. Let us understand it with the help of an example.
Source Code
const person = {
name: "John Doe",
salry: 200000,
workHistory: {
php: 7,
node: 4,
},
};
// accessing property of person object
document.write(person.workHistory);
//output: {php: 7, node: 4}
// accessing property of marks object
document.write("output: " + person.workHistory.php);
//output: 7
Javascript provides flexibility to add and remove the property to the existing object.
The following example creates a new object i.e person. Later, we will add a new property getInfo which is actually a function.
Source Code
let person = {
name: "John Doe",
age: 32,
job: "web developer",
};
console.log(person);
//Adding a new property
person.getInfo = function () {
return "My name is " + this.name + " and my age is " + this.age + " and my salary is " + this.job;
};
console.log(person.getInfo());
console.log(person);
Javascript property can be deleted using the delete
statement. Let us delete the job property from the person object.
Source Code
let person = {
name: "John Doe",
age: 32,
job: "web developer",
};
console.log(person);
//Deleting age
delete person.job;
console.log(person);