how to avoid “undefined” appearing in a string when a string is not defined- Javascript

Tags:



I have 3 variables which are dynamic and might be null or undefined.

Example:

var str1= " hello";
var str2= " world";
var str= " how are you?";

and now I’m concatenating these string together to form a query in my searchlist:

query = str1&& str1 + str2&& str2 + str3&& str3; //o/p: "hello world how are you?

this results fine, however in any case when one of the str value is null or empty, I get this whe I concatenate these string:

query = str1&& str1 + str2&& str2 + str3&& str3; // o/p: "hello world undefined"

How can I avoid this undefined coming in my string?

Answer

You can use the logical or operator to provide a default value in case any string is null or undefined.

query = (str1 || '') + (str2 || '') + (str3 || '')

You can use the nullish coalescing operator to only provide default values for null and undefined and not for other falsey values. Remember to check the browser support.

query = (str1 ?? '') + (str2 ?? '') + (str3 ?? '')


Source: stackoverflow