0

I made a mistake with writing the methods. But it still works and is way shorter is it allowed to write it like this?

var Mark = {
  firstName: 'Mark',
  lastName: 'Wielstra',
  mass: 78,
  height: 1.69,
  calculateBMI() {
    this.bmi = this.mass / (this.height * this.height);
    return this.bmi;
  }
}

Instead of this:

var Mark = {
  firstName: 'Mark',
  lastName: 'Wielstra',
  mass: 78,
  height: 1.69,
  calculateBMI: function() {
    this.bmi = this.mass / (this.height * this.height);
    return this.bmi;
  }
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • afaik, javascript tends to parse whatever anyway! A better question would be "in what scenario will this code crash" – Bizhan Sep 08 '18 at 10:33

1 Answers1

0

This is (somewhat new) syntax introduced in EcmaScript 2015:

Given the following code:

var obj = {
  foo: function() {
    /* code */
  },
  bar: function() {
    /* code */
  }
};

You are now able to shorten this to:

var obj = {
  foo() {
    /* code */
  },
  bar() {
    /* code */
  }
};

So yes, it is allowed and equivalent to the old (more verbose) syntax.

melpomene
  • 84,125
  • 8
  • 85
  • 148