7

In javascript I have the following:

var inf = id + '|' + city ;

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

Is there any slick way of saying if id or city are null make then blank.

I know in c# you can do the following:

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

Any similar method in javascript?

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Nate Pet
  • 44,246
  • 124
  • 269
  • 414
  • Your question is a bit confusing. Please provide one ore more example values for `inf`. – Felix Kling Apr 06 '12 at 15:52
  • possible duplicate of [null coalescing operator for javascript?](http://stackoverflow.com/questions/476436/null-coalescing-operator-for-javascript) –  Apr 06 '12 at 16:26

7 Answers7

22

How about:

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

EDIT: You can remove the "blank" parts before joining, so that if only one of id and city is null, inf will just contain that part and if both are 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
psyho
  • 7,142
  • 5
  • 23
  • 24
16

Total long shot, but try this:

var inf = (id || "") + "|" + (city || "");
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123
5
var inf = (id == null ? '' : id) + '|' + (city == null ? '' : city)
Philipp
  • 1,425
  • 1
  • 11
  • 23
1
function nullToStr(str) {
    return !str || 0 === str.length ? '' : str;
}

usage:

console.log(nullToStr(null);

        function nullToStr(str) {
    return !str || 0 === str.length ? '' : str;
}

console.log(`The value which was null = ${nullToStr(null)}`);
console.log(`The value which was null = ${nullToStr(undefined)}`);
console.log(`The value which was null = ${nullToStr('')}`);
console.log(`The value which was null = ${nullToStr('asdasd')}`);

I think it will help and is much easier to use. Obviously, it is based on the other answers i found in this thread.

Steve Johnson
  • 3,054
  • 7
  • 46
  • 71
0
var inf = (id && city) ? (id+"|"+city) : "";
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • What if one or the other is null? He wanted each variable replaced with `""` if it was null, not the whole thing. – gen_Eric Apr 06 '12 at 16:00
  • @Rocket "if id or city are null then inf will be null", I think he wants empty string either one is null. – xdazz Apr 07 '12 at 05:41
0

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

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

This is referred to as 'Short-Circuit Evaluation'. Nullability is not an issue in javascript (in js all variables are nullable), but id and city have to be assigned (but do not need a value, as in var id, city).

KooiInc
  • 119,216
  • 31
  • 141
  • 177
0
if (id != ""){
inf = id;
if (city != ""){ inf += " | " + city ;}
}
else 
inf= city;