Situation
I want to concatenate string variables and string arrays in TypeScript like in this simple example:
// var1, var2: string
// arr1: string[]
const myString = 'result:' + var1 + ' ' + arr1.join(' ') + ' ' var2;
I don't want multiple spaces concatenated together and there shouldn't be any spaces at the end.
Problem
It is possible that those variables are set to '' or that the array is empty. These leads to multiple spaces concatenated together which I want to avoid.
Question
Is there a more elegant way to concatenate only the set variables separated with exactly one space?
Conditions
- The solution should work with more variables/arrays
- The solution should be a one-liner
const myString = 'result:' + [var1, ...arr1, var2].filter(s => s?.length ?? 0 > 0).join(' ');s?and??and how they work? Thank you in advance.s?.lengthevaluates toundefined ifs` isundefinedornull, wheres.lengthwould throw.??a fallback0 > 0part?sisnullorundefinedthens?.lengthwill evaluate toundefinedAndundefined > 0evaluates tofalse(as doesundefined < 0) sos?.length ?? 0specifies that0should be used as a fallback. The thought here is to treatnullorundefinedvalues as if they were empty strings, filtering them out.