In this post, we will see how to resolve Shorthand for conditionally creating an array out of an optional value?
Question:
I have a function that optionally accepts an array. I have other variables that may beundefined
, but if they are defined I would like to create an array from it:temp
variable with an an array of strings
or pass undefined
? I tried to do the following but didn’t achieve it:Best Answer:
As it was pointed out in the comments, just create a helper function for this:Also, thanks to pilchard in the comments for noting that it is better to use a generic, rather than just the
string
type in your question or the any
type. Also, JDB for noting you must use !== undefined
, rather than simply checking for a falsy value (as the original question does).If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com
Leave a Review