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); }
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 = '';
}
var companyString="";
if(utils.htmlEncode(item.companyname) != null)
{
companyString = utils.htmlEncode(item.companyname);
}
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.log
to 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.