What is the prettiest way to concatenate String with potential null or undefined object without falling into this problem [...]?
There are several ways, and you partly mentioned them yourself. To make it short, the only clean way I can think of is a function:
const Strings = {};
Strings.orEmpty = function( entity ) {
return entity || "";
};
// usage
const message = "This is a " + Strings.orEmpty( test );
Of course, you can (and should) change the actual implementation to suit your needs. And this is already why I think this method is superior: it introduced encapsulation.
Really, you only have to ask what the "prettiest" way is, if you don't have encapsulation. You ask yourself this question because you already know that you are going to get yourself into a place where you cannot change the implementation anymore, so you want it to be perfect right away. But that's the thing: requirements, views and even envrionments change. They evolve. So why not allow yourself to change the implementation with as little as adapting one line and perhaps one or two tests?
You could call this cheating, because it doesn't really answer how to implement the actual logic. But that's my point: it doesn't matter. Well, maybe a little. But really, there is no need to worry because of how simple it would be to change. And since it's not inlined, it also looks a lot prettier – whether or not you implement it this way or in a more sophisticated way.
If, throughout your code, you keep repeating the ||
inline, you run into two problems:
- You duplicate code.
- And because you duplicate code, you make it hard to maintain and change in the future.
And these are two points commonly known to be anti-patterns when it comes to high-quality software development.
Some people will say that this is too much overhead; they will talk about performance. It's non-sense. For one, this barely adds overhead. If this is what you are worried about, you chose the wrong language. Even jQuery uses functions. People need to get over micro-optimization.
The other thing is: you can use a code "compiler" = minifier. Good tools in this area will try to detect which statements to inline during the compilation step. This way, you keep your code clean and maintainable and can still get that last drop of performance if you still believe in it or really do have an environment where this matters.
Lastly, have some faith in browsers. They will optimize code and they do a pretty darn good job at it these days.