Ternar to return undefined?

I want to include a property in an object only if a variable is defined. I do not want the property to remain at all. I donโ€™t even want it to equal an empty string. I think something like this:

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

If myVar is undefined, I want this to result in the same as below:

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

Am I doing it right?

+4
source share
4 answers

There is a difference between this:

 var ex1 = {foo: undefined}; 

and this:

 var ex2 = {}; 

Therefore, how would I do this:

 var args = { bing: 'bing', boom: 'boom' }; if (typeof myVar !== 'undefined') { args.bang = myVar; } someFunc(args, 'yay'); 
+5
source

i would do something like

 var config = { bing: "bing", boom: "boom" }; if (typeof myVar !== 'undefined') config.bang = myVar; someFunc(config, 'yay'); 

You must be careful with the truth and falsity of JavaScript. The if statement in my example only sets bang on config if myVar is defined, but it works if myVar is false.

+3
source

The best way to do this is

 var args = { bing: "bing", bang: myVar, boom: "boom" } if (myVar === undefined) { delete args.myVar; } someFunc(args, "yay"); 

It is clear that adding it when it exists is better and then removing it when it does not exist.

The bottom line is to handle something like this, really not, itโ€™s safer to use native delete to remove a property from an object.

You can crack it with setTimeout and callbacks. I recommend repeating this

 var args = { bing: 4, bang: (myVar === undefined) ? (function() { setTimeout(function() { delete args.bang; }, 0); })() : myVar }, "yay"); 
0
source
 var obj = { bing: "bing", boom: "boom" } myVar != null && obj.bang = myVar; someFunc(obj, "yay"); 

The above code does its job. I do not think that you can do this directly inside a function call.

0
source

Source: https://habr.com/ru/post/1337526/


All Articles