-2

Ternary operator does not work inside Objects. its show false out despite condition being true. I tried it with function and it works just fine.

'use strict';

const person = {
  age: 31,
  statement: this.age >= 30 ? 'true output' : 'false output'
};

console.log(person.statement)

1 Answers1

-1

in this example, this refers to window object use it as below:

const person = {
  age: 31,
  statement: person.age >= 30 ? 'true output' : 'false output'
};

if you want to use this, you have to use it within a function:

const person = {
  age: 31,
  statement: function(){
    return this.age >= 30 ? 'true output' : 'false output'
  }
};

then call it as function:

person.statement(); //result true output
Milad
  • 51
  • 9