1

I am trying to learn JavaScript and JSON and I don't understand these lines of code. Is total a method of the object and why? What are these functions called so I can learn more about them?

let price = {
  dollars: 9,
  cents: 99,
  total: function () {
    return this.dollars + this.cents/100;
  }
};
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 3
    First thing to learn about JSON, is that [object literals are not JSON](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). – Ivar Apr 24 '21 at 09:37
  • Yes, this is a method. This can also be written as `total() { return this.dollars + ...... }` without the `: function()` part: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#method_definitions – adiga Apr 24 '21 at 09:50

2 Answers2

1

let price = {} is called an Object initializer using shorthand object initialisation in literal notation

  • total is a property or object method of the price object

NOTE: You will not have any JSON until you JSON.stringify the object

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • wouldn't object initializer be all `dollars: 9, cents: 99, total: function () {return this.dollars + this.cents/100; }` and not the only the method OP is asking? – eis Apr 24 '21 at 09:38
  • 1
    @eis Please see update. I was not clear enough – mplungjan Apr 24 '21 at 09:39
0

This function is called Object method, so it is actually a method of the object.