Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary to return undefined?

I want to include a property on an object only in the event that a variable is defined. I don't want the property at all otherwise. I don't even want it to equal a blank string. I'm thinking something like this:

someFunc({
    bing: "bing",
    bang: (myVar) ? myVar : undefined,
    boom: "boom"
    }, "yay");

In the event that myVar is undefined, I want this to result in the same thing as the below:

someFunc({
    bing: "bing",
    boom: "boom"
    }, "yay");

Am I doing it right?

like image 579
Matrym Avatar asked Jan 20 '23 15:01

Matrym


2 Answers

There is a difference between this:

var ex1 = {foo: undefined};

and this:

var ex2 = {};

Therefore, here's how I would do it:

var args = {
    bing: 'bing',
    boom: 'boom'
};

if (typeof myVar !== 'undefined') {
    args.bang = myVar;
}

someFunc(args, 'yay');
like image 151
Matt Ball Avatar answered Jan 29 '23 08:01

Matt Ball


i would do something like

var config = {
    bing: "bing",
    boom: "boom"
};

if (typeof myVar !== 'undefined') config.bang = myVar;

someFunc(config, 'yay');

you have to be careful of javascript truthiness and falsiness. The if statement in my example only puts bang on config if myVar is defined, but it works if myVar is defined as false.

like image 28
hvgotcodes Avatar answered Jan 29 '23 08:01

hvgotcodes