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.
CodePudding user response:
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.
CodePudding user response:
You can check if an array exists by testing if it is false-y. Thus, you can create an array if it doesn't already exist with
arr = (arr || []);
From there you can just push your new element:
arr = (arr || []);
arr.push(elt);
CodePudding user response:
if(arr && arr.length > 0) {
arr.push(elt);
//or can use spread operator
arr = [...arr, elt];//this should work if I am not wrong
}
else {
arr = [elt];
}
It is somewhat similar but I guess it should work fine and is a general pattern.