DEV Community

SCDan0624
SCDan0624

Posted on

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.

Top comments (0)