1

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!

1
  • 1
    It would probably be best if you didn't write it this way... Commented May 25, 2021 at 21:57

4 Answers 4

2

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');
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

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)

2 Comments

This won't work - he wants to default if it's null or empty. '' ?? '1' === ''
@dave Thanks for that, forgot about this. Already updated answer.
2

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}`;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.