Search code examples
javascriptejsembedded-javascript

Skip undefined values in if statement and loop


I'm trying to loop through all user's comments, but with an if statement looking for a certain value. Problem is my app breaks as some users havent made comments, and therefore i get a 'cannot read property of 'collected' undefined. How do I skip over undefined values for the if statement? the code is below:

<% for(var i=0; i < users.length; i++) { %>
   <tr>


    <% if(users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>

     <td>Nothing in reception - well done!</td>

    <%  } else { %>



     <td><%= users[i].studio %></td>
     <td><%= users[i].name %></td>
     <td><%= users[i].email %></td>
     <td><%= users[i].username %></td>
     <td><%= users[i].comments.slice(-1)[0].collected %></td>

     <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>

    <% } %>

Solution

  • Just add a check to see if the object exists, and if the comments length is > 0:

    <% for(var i=0; i < users.length; i++) { %>
       <tr>
    
        <% if(!users[i].comments || users[i].comments.length == 0) {
              continue;
        } else if(users[i].comments && users[i].comments.length > 0 && users[i].comments.slice(-1)[0].collected !== 'At Reception') { %>
    
         <td>Nothing in reception - well done!</td>
    
        <%  } else { %>
      <% console.log('nothing in reception') %>
    
     <td><%= users[i].studio %></td>
     <td><%= users[i].name %></td>
     <td><%= users[i].email %></td>
     <td><%= users[i].username %></td>
     <td><%= users[i].comments.slice(-1)[0].collected %></td>
    
     <td><a class="btn btn-primary" href="/users/<%= users[i]._id %>">More Info</a></td>
    
    <% } %>