Objects in Java Script

Objects in Java Script

Objects :

Objects in javascript are one of the non-primitive datatypes which allow us to store multiple values in key-value pairs. These key-value pairs are known as properties. The key is also called as property name and the value is also called the property value. Objects are the most used data type in JavaScript. Objects make it easy to work with data.

In simple words, it can be said an object is a collection of data in the form of key-value pairs. Objects have keys and every key has a corresponding value.

These values can be as simple as a number or string or maybe some complex types like function or even another object itself.

Let's for example if we want to store the names of cricketers we will use an array on the other hand if we want to store names, matches played and runs scored by cricketers then an object is used.

Syntax :

An object is created by first declaring the variable declaration then the name of the object after that = sign and curly {}. Here in this case an empty object is created. An empty object is called an object literal.

Lets us Understand this with an Example :

const cricket = {
    name1:'Virat Kohli',
    matchesplayed:'100',
    runsscored:'2000',
    currentsataus: true
 };
 console.log(cricket);

Here, in this case, an object is created by the name of cricket. name1, matches played, run scored, and current status are the keys and Virat Kohli,100,2000 and true are the values of the respective keys and all the key-value pairs are separated by commas.

The combination of both key and values are called the property of an object.

The Output of the above is :

{
  name1: 'Virat Kohli',
  matchesplayed: '100',
  runsscored: '2000',
  currentsataus: true
}

Objects using Constructor :

const kapil =new Object(); //declaration of object using constructor

 kapil.country='India'
 kapil.religion='Hindu'
 console.log(kapil);

The Output is :

{ country: 'India', religion: 'Hindu' }

Accessing Properties of an Object :

There are two ways by which the properties of an object can be accessed.

Dot Notation :

To get the value of a property from an object, we can use a dot (.). A syntax is an object. property

const details = {
   fname:'Kapil',
   lname:'Sarkar',
   coutntry :'India'
 };
 console.log(details.fname);
 console.log(details.lname);
 console.log(details.coutntry);

The Output is :

Kapil
Sarkar
India

Bracket Notation :

We can also get the value of a property using [ ].

const details = {
   fname:'Kapil',
   lname:'Sarkar',
   coutntry :'India'
 };
console.log(details['fname']);

The Output is :

Kapil

Update of Properties in an Object :

In the object the existing properties can be updated and also new properties can be added.

Adding New Properties to an existing Object :

Before Adding New Properties the code for an existing object :

const mydetails={
    fname:'Kapil',
    lname:'Sarkar',
    address:'Asansol'
}

Now New Properties are being added :

mydetails.phoneno=9999999999;
console.log(mydetails);

The Output achieved is :

{
  fname: 'Kapil',
  lname: 'Sarkar',
  address: 'Asansol',
  phoneno: 9999999999
}

Update of Property in an existing Object :

Before the Updation of New Properties the code for an existing object :

const mydetails={
    fname:'Kapil',
    lname:'Sarkar',
    address:'Asansol'
}

Now the existing property is being updated.

mydetails.address='Burnpur';
console.log(mydetails);

The Output achieved is :

{ fname: 'Kapil', lname: 'Sarkar', address: 'Burnpur' }

Deletion of Property in an existing Object :

const mydetails={
    fname:'Kapil',
    lname:'Sarkar',
    address:'Asansol'
}

The Output Achieved is :

{ fname: 'Kapil', address: 'Asansol' }

Creating Methods in Java Script :

Functions in objects are called methods

const mydetails={
    fname:'Kapil',
    lname:'Sarkar',
    address:'Asansol',
    getaddress(){
        console.log(`Address is :${mydetails.address}`);
    }
}
mydetails.getaddress();

Here a method is declared by name get address (). The method is invoked by my details getaddress()

The Output is :

Address is :Asansol

Creating Nested Objects :

const details ={
    mydetails :{
        fname :'Kapil',
        lname :'Sarkar',
        address:'Asansol',
        myinfo:{
            education:'MCA',
            rolemode:'Sachin Tendulkar',
        }

    }
};  console.log(details);

The Output is :

{
  mydetails: {
    fname: 'Kapil',
    lname: 'Sarkar',
    address: 'Asansol',
    myinfo: { education: 'MCA', rolemode: 'Sachin Tendulkar' }
  }
}

For in Loop :

For in Loop is used in Java Script in case of Object. Here with the help of for in loop, the properties of the objects are fetched and printed.

let mydetails={
    fname:'Kpail',
    lname:'Sarkar',
    address:'Asansol'
 }
 for(let x in mydetails){
    console.log(x);
 }
 for (let x in mydetails){
    console.log(mydetails[x]);
 }

The Output is :

fname
lname
address
Kpail
Sarkar
Asansol

Object. create() :

Objects can also be created using the Object. create() method.

This method can be very useful because it allows you to choose the prototype object for the object, you want to create, and in this, we do not have to define a constructor function.

Let us understand this with an example :

let cricket={
      batsman:true,
      bowler:true,
 };
 let sports=Object.create(cricket);

 console.log(sports.batsman);
 console.log(sports.bowler);

The Output is :

true
true

Object .defineProperty() :

In JavaScript is a standard built-in Object that defines a new or modifies existing properties directly on an object and it returns the object.

Syntax :

Object.defineProperties(obj, props)

Here the two parameters passed are :

obj: This parameter holds the object on which the properties are going to be defined or modified.

props: This parameter is an object whose own enumerable properties constitute descriptors for the properties to be defined or modified.

Let us understand this with an Example :

const myname={}
myname.fname='Kpail Sarkar';
console.log(myname);

The Output is :

{ fname: 'Kpail Sarkar' }

Now let us understand the same thing by Object.defineProperty()-

const myname={}
Object.defineProperty(myname,'fname',{
   value:'Kapil',
   writable:false
})
myname.fname='Kapil Sarkar';
console.log(myname.fname);

Notice, we define the property just like the first case but later we change the value of the property to 'Kapil Sarkar' and print the value but it is not changed. This happened due to the attribute defined writable: false for this. It could restrict the modification and the value is still the same. So, it is a kind of advanced method, we can say.

Here only Kapil is printed so the Output is :

Kapil

Now if the writable property is set to true then :

const myname={}
Object.defineProperty(myname,'fname',{
   value:'Kapil',
   writable:true
})
myname.fname='Kapil Sarkar';
console.log(myname.fname);

The Output is :

Kapil Sarkar

this Keyword :

this refers to the parent scope. Here, we should remember one thing we can't use the arrow function as the arrow function does not have the context for this.

const details={
   fname:'Kapil',
   lname:'',
   fulldetails : function() {
      this.lname += 'Sarkar';
      return this;
   },
};
console.log(details.fulldetails());

The Output is :

 fname: 'Kapil',
  lname: 'Sarkar',

Chaining of Function :

const details={
   fname:'Kapil',
   lname:'',
   fulldetails : function() {
      this.lname += 'Sarkar';
      return this;
   },
};
console.log(details.fulldetails().fulldetails().fulldetails());

The Output is :

fname: 'Kapil',
  lname: 'SarkarSarkarSarkar',

getters and setters in Java Script :

Accessor properties are represented by “getter” and “setter” methods. In an object literal they are denoted by get and set.

Syntax :

let obj = {
    get propName() {
       // getter, the code executed on getting obj.propName
     },

     set propName(value) {
       // setter, the code executed on setting obj.propName = value
     }
   };

Now let us understand this with an example :

let details={
   fname:'Kapil',
   lname:'Sarkar',

   get mydetails(){
      return `${this.fname} ${this.lname};`
   } ,
   set mydetails(value){
      [this.fname,this.lname]=value.split(' ');
   }
};
console.log(details.mydetails.split(' '));

The Output is :

[ 'Kapil', 'Sarkar;' ]