Using conditions inside JavaScript

Tags: ,



I have this infinite scroll code which works perfectly fine.

I m trying to use if-else conditions inside my Code but due to some syntax (i think) error its not echoing out.

My code goes as :

function addrows(rows) {
        let postList = $("#post-list");
        $.each(rows, function (i, row) {
            var img = row.image;
            let rowHtml = `
                 <div class="mt-3">
             `+if (img == null){ +`
                    <a href="post?id=`+row.id+`" style="color:black;">
                       <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+row.title+`</p>
                    </a>
             `+} else { +`
                    <a href="post">
                       <img src="images-main/images/`+row.image+`" alt="post-image" class="img-fluid rounded w-100">
                    </a>
              `+}+`
                 </div>
           `;
                        
            postList.append(rowHtml);            

        });
    }

Please note that the whole infinite scroll code works fine if I m to remove those if-else conditions.

Any help is greatly appreciated.

Answer

You can not concat the if else with the string, it is not valid syntax in javascript, either you can use the ternary conditional operator or using if else like this

  let postList = $("#post-list");
  $.each(rows, function (i, row) {
    var img = row.image;
    let rowHtml = `<div class="mt-3">`;
    if (img == null) {
      rowHtml += `<a href="post?id=` + row.id + `" style="color:black;">
                      <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+ row.title + `</p>
                  </a>`;
    }
    else {
      rowHtml += `<a href = "post" >
                      <img src="images-main/images/`+ row.image + `" alt = "post-image" class="img-fluid rounded w-100" >
                  </a>`;
    }
    rowHtml += '< /div>';
    postList.append(rowHtml);
  });
}


Source: stackoverflow