JS: Define method

By Xah Lee. Date: . Last updated: .

Define method

A method is just a Property that has value of Function .

// A method is just a Property that has value of Function .
const jj = {
 add1: function (x) {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4
const jj = {
 // method shorthand syntax
 add1(x) {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4
// method by arrow function
const jj = {
 add1: (x) => {
  return x + 1;
 },
};

// calling the method
console.log(jj.add1(3));
// 4
// method can be added later as a property

const jj = { name: "Alice" };

jj.add1 = (x) => {
 return x + 1;
};

// calling the method
console.log(jj.add1(3));
// 4

// get property
console.log(jj.name);
// Alice