DEV Community

SCDan0624
SCDan0624

Posted on

2 1

Intro to Objects Part 2: Methods

Writing Methods in Objects
Another cool feature in objects is the ability to write a method. Writing a method is when you add functions as a property on an object. Here is an example:

const math = {
  add: function (num1,num2) {
     return num1 + num2
  }
}
Enter fullscreen mode Exit fullscreen mode

To call these functions we use a combination of accessing the object and invoking the function

const math = {
  add: function (num1, num2) {
     return num1 + num2
  }
}

math.add(5,5)

// 10
Enter fullscreen mode Exit fullscreen mode

Even if you have multiple methods this will work

const math = {
  add : function(num1, num2){
    return num1 + num2;
  },
  sub: function (num1,num2){
    return num1 - y;
  }
}

math.add(5,5) // 10
math.sub(10,2) // 8
Enter fullscreen mode Exit fullscreen mode

Shorthand

While the above syntax works perfectly fine there is new shorthand syntax you can use as well.

const math = {
  add(num1,num2){
  return num1 + num2;
  },
  sub(num1,num2){
  return num1 - num2;
  }
}

math.add(5,5) // 10 
math.sub(10,2) // 8
Enter fullscreen mode Exit fullscreen mode

Conclusion
Now you know how to write and use methods, using traditional or short hand syntax. For part 3 you will learn how to use the This keyword with objects.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay