Hello, enthusiastic developers today I will take a deep dive into the JavaScript object. Let's start.....
First of all, in JavaScript Object is called king. Anyone who can understand object property can understand JavaScript easily.
An object in JavaScript is a collection of key-value sometimes called name-values. Each key-value pair is called a property. A property can be a function, an array, an object itself, or any primitive data type such as an integer, or string.
const player = {
firstName: "David",
lastName: "Cameron",
age:30,
fullName: function(){
return this.firstName + " "+ this.lastName
}
}
Way of access of object property:
There are two ways of accessing object property
1.Dot notation
2.Square bracket notation
Dot Natation
player.firstName // output is David
player.fullName() //output is David Cameron
Square bracket Notation
player["firstName"] // output is David
player["age"] //output is 30
*Notes: * Another way of accessing objects is
let x= "age"
player[x]
Delete object property:
To delete a property from an object we can use the delete keyword.
delete player.firstName//return true and delete firstName property
Let's see what happens if we try yo call the fullName method which uses both firstName and lastName property of the player object but we have deleted the firstName
console.log(player.fullName()) //output is undefined Cameron
output return undefined in firstName because we trying to access a property of the player object that does not exist.
Object Method:
A function that is used as an object property is the call method.
const player = {
firstName: "David",
lastName: "Cameron",
age:30,
fullName: function(){
return this.firstName + " "+ this.lastName
}
}
here fullName() is an object method.
To check if an object has a property using the hasOwnProperty method. When the property is available in the object it will return true otherwise return false.
console.log(player.hasOwnProperty('firstName')) //output is true
console.log(player.hasOwnProperty('middleName')) //output is false
To loop through the properties of an object use normally for...in loop.
const player = {
firstName: "David",
lastName: "Cameron",
age:30,
fullName: function(){
return this.firstName + " "+ this.lastName
}
}
for (let x in player) {
console.log(player[x])
}
//output is
David
Cameron
30
[Function: fullName]
A constructor function is a function that is used to create new objects with the same properties and methods.
function player(name,age){
this.name = name,
this.age =age
}
let x = new player ('Messi',35)
let y = new player ('Ronaldo',37)
function player(name,age){
this.name = name,
this.age =age
}
let x = new player ('Messi',35)
let y = new player ('Ronaldo',37)
console.log(x)
console.log(y)
//output is
player { name: 'Messi', age: 35 }
player { name: 'Ronaldo', age: 37}
Top comments (0)