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?
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With