ThomasReggi
ThomasReggi

Reputation: 59365

conditional variable in object

Just tried to do something like this and it wont work, wondering if there is anyway?

var obj = {
    intiger:5,
    conditional:(something) ? "something" : "nothing",
    string:"nothing important"
};

This is breaking because of the presence of the : within the conditional. Anyway to do this without it breaking and keeping this format of obj.

I know that I can do.

obj.conditional = (something) ? "something" : "nothing";

Upvotes: 1

Views: 3414

Answers (1)

Brad Christie
Brad Christie

Reputation: 101614

Use another set of parenthesis?

...
conditional:((something)?"something":"nothing"),
...

Just have to let the parser know which : to pay attention to and for which purpose.

var foo = {
    bar: (true ? "true" : "false")
};
console.log(foo.bar); // true

You can also use a function(){} if the decision needs to be made at the time of reference. e.g.

var foo = {
    bar:function(){
        return this.baz == 'Brad' ? 'Me' : 'Not Me';
    },
    baz: 'Brad'
};
console.log(foo.bar()); // 'Me'
foo.baz = 'Thomas'; console.log(foo.bar()); // 'Not Me'

Upvotes: 4

Related Questions