Aug 14, 2017

QuickTip JS : avoid bad string building using Short-circuit

Hello Dev fellows,

I wanted to share a quicktip that could prevent you from having troubles with string building. Let's suppose we want to display the Full name of a person according to its personal information :

sample1.png sample1_output

The falsy values "undefined", "null" (or "" or 0) are stringified and concatenated in the output string. It would be way more elegant to give them a default value with a coalesce operator (just like in C#). Actually there is not such an operator in JS, but you can use the short-circuit technique : value || "Default value"

Let's adapt the code

last_code_change last_code_change-output

And you avoid that way to have crappy string parts.

Hope it is useful

See ya

Yannick

Other posts