DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

JS Object

What is Object?

  • An object is a collection of key-value(properties and values) pairs.
  • In other terms they are variables that can store both values and functions.
  • Functions are stored as key:function() pairs called methods.
const person = {
    name : "Varun", 
    age : 6, 
    isStudent : true
};

document.write(person.name+"<br>");
document.write(person.age+"<br>");
document.write(person.isStudent+"<br>");


Output : 
Varun
6
true

//Here name,age and isStudent are keys. Varun,6 and true are values.

Enter fullscreen mode Exit fullscreen mode

Accessing object keys using Bracket Notation(useful for dynamic keys) :

const person = {
    name : "Varun", 
    age : 6, 
    isStudent : true
};

document.write(person["name"]+"<br>");
document.write(person["age"]+"<br>");
document.write(person["isStudent"]+"<br>");

Output :
Varun
6
true

Enter fullscreen mode Exit fullscreen mode

Adding and Updating property :

const person = {
    name : "Varun", 
    age : 6, 
    isStudent : true
};

person.city = "chennai"; //adding new property
person.age = 7 //updating property

document.write(person.name+"<br>");
document.write(person.age+"<br>");
document.write(person.isStudent+"<br>");
document.write(person.city+"<br>");

Output : 
Varun
7
true
chennai

Enter fullscreen mode Exit fullscreen mode

Deleting property :


const person = {
    name : "Varun", 
    age : 6, 
    isStudent : true
};

console.log(person.isStudent);
delete person.isStudent
console.log(person.isStudent); //undefined

Enter fullscreen mode Exit fullscreen mode

Methods(Functions inside objects) :

const person = {
    name: "Varun",
    age:6,
    greet: function(){
        return "Hi, I am "+this.name+"."; //'this' refers to this object
    },
    play:()=>{
        return "I am Playing."
    }

};

document.write(person.greet()+"<br>");
document.write(person.play());

Output :
Hi, I am Varun.
I am Playing.

Enter fullscreen mode Exit fullscreen mode

Nested objects :

  • A Nested Object is simply an object inside another object.
const person = {
    name: "Varun",
    age:6,
    address :{
        city: "Chennai",
        state: "Tamilnadu"
    }

};

document.write(person.address.city+"<br>");
document.write(person.address.state);

Output :
Chennai
Tamilnadu

Enter fullscreen mode Exit fullscreen mode

Top comments (0)