-1

I working with legacy code which uses underscore. I am trying to add an if else statement to the code which will check if the json is returning any value or not and if it doesn't it will return no value (hence the empty div).

Here is my code:

<% if(!_.isNull(datas.Recent)) {%>
<div></div>
<% } else { %>
<div class="contents"><%=datas.Recent%</div>
<% } %>

This code seems to be running the if statement exclusively which confuses me because of the code.

<% if(datas.Recent) {%>
<div class="contents><%=datas.Recent%</div>
<% } %>

Does return value/works as it was part of the original legacy code. Any idea what I am doing wrong with my use of the if else statement?

sacora
  • 265
  • 1
  • 3
  • 8

2 Answers2

1

It's likely that your datas.Recent is some falsey value, but not null. If it is false, an empty string, or (most likely) undefined, it is falsey, but not null. For example:

var notanull = false;
console.log(!notanull); // true
console.log(notanull === null); // false
console.log(!_.isNull(notanull)); // false

More likely, you are dealing with an object property that has not been given a value. That would be undefined.

var obj = {one: 'two'};
console.log(obj.three); // undefined
console.log(typeof(obj.three)); // 'undefined'

console.log(!obj.three); // true
console.log(obj.three === null); // false
console.log(_isNull(obj.three)); // false
arbuthnott
  • 3,819
  • 2
  • 8
  • 21
0

Have not worked with any legacy code like that but seems to me that

if(!_.isNull(datas.Recent))

will return false if it's null. If I were the one writing the code isNull returns true if the input is null, and you have a not flag in front of it.

Edit: If I'm right changing it to

if(_.isNull(datas.Recent))

would fix it.

Asgeirr
  • 82
  • 10