skip to Main Content

I have an object that either contains an image URL or not.

{
    id: 1,
    term: "Research",
    imageURL: "",
    definition:
      "is a way of thinking and understanding various aspects of a procedure to society.",
  }

I created a function that is supposed to read whether the imageURL is not empty then show the image and if yes, show different content, but it throws an error that says,

"This condition will always return ‘false’ since JavaScript compares
objects by reference, not value. ts(2839)"

const imageURL = item.imageURL

{ imageURL === "" ? (shows with no image) : (shows with image)}

Is there a way to read the object’s property that contains a string whether its empty or not? Thank you!

2

Answers


  1. I’ve been using the length property lately, and it is working fine.

    const object = { 
        id: 1, 
        term: "Research", 
        imageURL: "", 
        definition: "is a way of thinking and understanding various aspects of a procedure to society.", 
    }
    
    object.imageURL.lenght ? render-image : render-default-content
    

    It will cast length as a number to a boolean. If the length is 0 it means the string is empty, if the length is >1 it will be true.

    Login or Signup to reply.
  2. It is bad practice to return empty strings. Better make a field "nullable". Better approach is to deal with existing and not existing values, because you do not need bad data.

    const object = { 
        id: 1, 
        term: "Research", 
        imageURL: undefined, 
        definition: "is a way of thinking and understanding various aspects of a procedure to society."
    }
    

    or

    const object = { 
        id: 1, 
        term: "Research", 
        definition: "is a way of thinking and understanding various aspects of a procedure to society."
    }
    

    and then check it:

    object.imageURL ? render-image : render-default-content
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search