0

my so far understanding with object literal is we can use it like the key value pair, where key is the property and the value can be a actual value, a function or a anonymous function

 function a() {
  return 'value b';
}

var result = {
  'keya': 'valueA',
  'keyb': a,
  'keyc': function () {
    console.log('some value');
  }

};

till i read this block of code

var obj = {
  log: ['test'],
  get latest() {
    if (this.log.length == 0) return undefined;
    return this.log[this.log.length - 1];
  }
}
console.log(obj.latest); // Will return "test".

my question is, in the above code the function latest() doesnt have any key then how can it be used inside a object literal, am i missing something

Lijin Durairaj
  • 3,341
  • 11
  • 31
  • 50
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters – Slai Aug 19 '17 at 05:51

1 Answers1

2

This is ES6 (which is also called ES2015) syntax, it's a newer version of Javascript that lets you do this.

You would've had to have the key there in ES5 code.

Nick Tamburro
  • 150
  • 1
  • 4
  • 16