How should I properly structure this "if" statement using jQuery?

I've written an if statement that checks if there is a current user and if so, grab that currentUser's profile image url from my DB and place it in a div. I've successfully done so with the following logic:

  function checkLogin() {

    if (Parse.User.current()) {
      var profilePicUrl = Parse.User.current().get("profile_picture").url();

      $(".user-image").css("background-image", "url("+profilePicUrl+")");
    } else {

      $(".user-image").css("background-image", "url(//default image)");
    }
  };

However the issue is, when there is a user that doesn't have a profile image, it throws an error. I've attempted to offset this by adding the following else if statement between the original two:

 function checkLogin() {

    if (Parse.User.current()) {
      var profilePicUrl = Parse.User.current().get("profile_picture").url();

      $(".user-image").css("background-image", "url("+profilePicUrl+")");

    } else if (Parse.User.current() && !profilePicUrl){

      $(".user-image").css("background-image", "url(//default image)");

    } else {

      $(".user-image").css("background-image", "url(//default image)");

    }
  };

Now I'm almost certain I'm using the && operator wrong here, but what I'm trying to say in the middle else if is "if there is a current user & they don't have a profile image ..."

How do I properly state this?

Answers 1

  • Actually, since parseObject.get() returns null if the key is not found, all you need here is:

     function checkLogin() {
        if (user = Parse.User.current()) {
          var profilePic = user.get("profile_picture");
          var profilePicUrl = profilePic ? profilePic.url() : "//default image";  
          $(".user-image").css("background-image", "url("+profilePicUrl+")");
        }
      };
    

    Note that the var someVar = someVar ? valueA : valueB; syntax is a Conditional (ternary) Operator


Related Articles