4

I get return value as null and assign that value it shows as null in the UI. But I want to check some condition and if it is null, it should not show up anything.. I tried the below code and it doesn't work

var companyString;
if(utils.htmlEncode(item.companyname) == null)
{
  companyString = '';
}
else{
  companyString = utils.htmlEncode(item.companyname);
}

2
  • why don't you just do var companyString=" "? Commented Jul 24, 2015 at 4:17
  • You should compare item.companyname to null (but probably really any false-y value), not the encoded form. Commented Jul 24, 2015 at 4:25

3 Answers 3

5

Compare item.companyname to null (but probably really any false-y value) - and not the encoded form.

This is because the encoding will turn null to "null" (or perhaps "", which are strings) and "null" == null (or any_string == null) is false.

Using the ternary operator it can be written as so:

var companyString = item.companyname
  ? utils.htmlEncode(item.companyname)
  : "";

Or with coalescing:

var companyString = utils.htmlEncode(item.companyname ?? "");

Or in a long-hand form:

var companyString;
if(item.companyname) // if any truth-y value then encode
{
  companyString = utils.htmlEncode(item.companyname);
}
else{                // else, default to an empty string
  companyString = '';
}
Sign up to request clarification or add additional context in comments.

Comments

0
var companyString;
if(item.companyname !=undefined &&   item.companyname != null ){
companyString = utils.htmlEncode(item.companyname);  
}
else{
companyString = '';
}

Better to check not undefined along with not null in case of javascript. And you can also put alert or console.logto check what value you are getting to check why your if block not working. Also, utls.htmlEncode will convert your null to String having null literal , so compare without encoding.

Comments

-1
var companyString="";
if(utils.htmlEncode(item.companyname) != null)
{
   companyString = utils.htmlEncode(item.companyname);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.