Search code examples
javascriptobject-literal

Can the Object literal take values other than key value pair?


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


Solution

  • 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.