Search code examples
javascriptobjectconditional-operator

Ternary Operator does not work inside an Object


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)


Solution

  • 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