Skip to content
Related Articles

Related Articles

Improve Article

How to create a function that invokes the method at a given key of an object in JavaScript ?

  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021

In JavaScript objects store variables in the key-value pair where the key is the property of the object and the value maybe the value of the property, or it may be any method that invokes when it is called.

In this article, we will learn to invoke a method that is provided to key.

Approach:

Generally, an external function can be defined to do the same, but we need to access every key of the object instead we can directly define a function to a key in the object and access the function only.

Syntax:



var objectName=
{
key1: value or method(),
key2: value or method(),
key3: value or method(),
...
}

Code: The following code snippet demonstrates to access Object.keys as myProfile.myName and myProfile.skills gets the name and skills for the object myProfile.

Javascript




<script>
  var myProfile={
       myName: 'Lokesh',
       skills: 'Web Development'    
  }
  
  let message=`My name is ${myProfile.myName} 
               and my skills are ${myProfile.skills}`;
  
  console.log(message);
</script>

Output:

My name is Lokesh and my skills are Web Development.

Declaring a function to a key of an object: The following code snippet demonstrates a function printProfile() for the object myProfile.

Javascript




<script> 
  
    var myProfile={
     myName: 'Lokesh',
     skills: 'Web Development',
      printProfile : function()
      {
       let message=`My name is ${this.myName} 
                    and my skills are ${this.skills}.`;
       return message;
      }
    }
  
    console.log(myProfile.printProfile());
  
</script>

Output:

My name is Lokesh and my skills are Web Development.

Note: The this keyword is used to access the same object key’s value and can be accessed using this.keyname.

Calculator by invoking the methods of keys in an object: The following code snippet demonstrates many functions’ adder(), subtractor(), multiplier(), divider() for the object calculator.

Javascript




<script>  
  var calculator={
      adder: function(num1,num2){
         let num=num1+num2;
         return num;
      },
      subtractor: function(num1,num2){
          let num=num1-num2;
          return num;
       },
      multiplier: function(num1,num2){
          let num=num1*num2;
          return num;
       },
       divider: function(num1,num2){
          let num=num1/num2;
          return num;
       }
  }
  console.log(calculator.adder(5,5));
  console.log(calculator.subtractor(5,5));
  console.log(calculator.multiplier(5,5));
  console.log(calculator.divider(5,5));
 </script>

Output:

 10
 0
 25
 1



My Personal Notes arrow_drop_up
Recommended Articles
Page :