In my code I have an element, and I want to have it in an array: either the array already exists and then I push my element, or it doesn’t and in that case I create the array with this only element:
if (arr) {
arr.push(elt);
} else {
arr = [elt];
}
I’m sure there is a better way to do this. I looked into spreading and nullish coalescing operator, but I didn’t find any correct syntax.
Does anybody have an idea on how I could write my lines with a nicer syntax?
Thanks in advance.
>Solution :
You can use the expression arr || [] to return an array which is either arr if arr is defined already or [] otherwise. Then you can simply concat the new value to it:
arr = (arr || []).concat([elt])
Note the new value needs to be enclosed in [] to prevent elt values which are arrays from being flattened.