Javascript null value in string

In javascript, I have the following:

var inf = id + '|' + city ; 

if id or city are null, then inf will be null.

Is there a slippery way of saying id or city are null and then null.

I know that in C # you can do the following:

 var inf = (id ?? "") + (city ?? ""); 

Any similar method in javascript?

+6
source share
6 answers
 var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city) 
+4
source

What about:

 var inf = [id, city].join('|'); 

EDIT: You can remove the "empty" parts before joining, so if only one of id and city is null, inf will only contain that part, and if both null inf will be empty.

 var inf = _([id, city]).compact().join('|'); // underscore.js var inf = [id, city].compact().join('|'); // sugar.js var inf = [id, city].filter(function(str) { return str; }).join('|'); // without helpers 
+20
source

Just a long shot, but try the following:

 var inf = (id || "") + "|" + (city || ""); 
+11
source
 var inf = (id && city) ? (id+"|"+city) : ""; 
0
source

Equivalent to C # var inf = (id ?? "") + (city ?? ""); (if id and city are nullable) is

 var inf = (id || '') + (city || ''); 

This is called a short circuit rating . Vulnerability is not a problem in javascript (in js all variables are nullable), but id and city must be assigned (but do not need a value like in var id, city ).

0
source
 if (id != ""){ inf = id; if (city != ""){ inf += " | " + city ;} } else inf= city; 
0
source

Source: https://habr.com/ru/post/912616/


All Articles