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 panyString;
if(utils.htmlEncode(itempanyname) == null)
{
panyString = '';
}
else{
panyString = utils.htmlEncode(itempanyname);
}
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 panyString;
if(utils.htmlEncode(item.panyname) == null)
{
panyString = '';
}
else{
panyString = utils.htmlEncode(item.panyname);
}
Share
Improve this question
asked Jul 24, 2015 at 4:15
Vetri ManoharanVetri Manoharan
511 gold badge1 silver badge5 bronze badges
2
-
why don't you just do
var panyString=" "
? – Guruprasad J Rao Commented Jul 24, 2015 at 4:17 -
You should pare
item.panyname
to null (but probably really any false-y value), not the encoded form. – user2864740 Commented Jul 24, 2015 at 4:25
3 Answers
Reset to default 5Compare item.panyname
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 panyString = item.panyname
? utils.htmlEncode(item.panyname)
: "";
Or with coalescing:
var panyString = utils.htmlEncode(item.panyname ?? "");
Or in a long-hand form:
var panyString;
if(item.panyname) // if any truth-y value then encode
{
panyString = utils.htmlEncode(item.panyname);
}
else{ // else, default to an empty string
panyString = '';
}
var panyString;
if(item.panyname !=undefined && item.panyname != null ){
panyString = utils.htmlEncode(item.panyname);
}
else{
panyString = '';
}
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 pare without encoding.
var panyString="";
if(utils.htmlEncode(item.panyname) != null)
{
panyString = utils.htmlEncode(item.panyname);
}