Skip to content
Advertisement

Javascript: How to concatenate 2 values treating undefined or null values as empty

This is what I want:

var str = data + unit; // data:"2", unit: "rem", I want str: "223"
var str = data + unit; // data:"2", unit: null, I want  str: "2"
var str = data + unit; // data:"2", unit: undefined, I want  str: "2"
var str = data + unit; // data:undefined, unit: "rem", I want str: "rem"

Input and output values are given in the comments against each line. Normal concatenation appends “undefined” as a literal string. I want undefined and null values to be treated as empty string

Advertisement

Answer

You can use the nullish coalescing operator to convert null or undefined to an empty string.

var str = (data ?? "") + (unit ?? "");

For better browser support, you may want to use the logical or operator instead.

var str = (data || "") + (unit || "");
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement