0

I am trying to check if the string is null or empty. If it is null or empty, then trying to assign default value as '1'. I tried below but it does not work.

var url = 'http://www.test.com?';
var concatResult = url +
    "&firstname=" + viewer[1] ? viewer[1] : '1' +
    "&tableId=" + this.id ? this.id : '1';

The output of concatResult is empty "" which should not be empty.

I would really appreciate your help. Thank you!

eko
  • 39,722
  • 10
  • 72
  • 98
CodeVenture
  • 157
  • 1
  • 16

4 Answers4

1

You need to wrap it in parenthesis:

(viewer[1] ? viewer[1] : '1')

Otherwise it is doing

(url + "&firstname=" + viewer[1]) ? viewer[1] : '1'

So all together:

var concatResult = url +
    "&firstname=" + (viewer[1] ? viewer[1] : '1') +
    "&tableId=" + (this.id ? this.id : '1');

Or a little shorter:

var concatResult = url +
    "&firstname=" + (viewer[1] || '1') +
    "&tableId=" + (this.id || '1');
dave
  • 62,300
  • 5
  • 72
  • 93
1
var url = 'http://www.test.com?';
var concatResult = url +
    "&firstname=" + (viewer[1] || '1') +
    "&tableId=" + (this.id || '1');
vincendep
  • 528
  • 4
  • 10
1

this is working, no need to use + signs and quotes, just use template strings (Template literals)

const viewer = []
const id = ""

const url = 'http://www.test.com?';
const concatResult = `${url}&firstname=${viewer[1] || 1}&tableId=${id || 1}`;
SebMaz93
  • 539
  • 1
  • 6
  • 14
1

You can use Nullish_coalescing_operator (?? and .?) or good old fashion or (||):

var viewer = null
var id = ''
var url = 'http://www.test.com?';
var concatResult = url +
    "firstname=" + (viewer?.[1] || '1') +
    "&tableId=" + (id || '1')
    
console.log(concatResult)
ulou
  • 5,542
  • 5
  • 37
  • 47