Search code examples
javascriptdiscorddiscord.jsembed

How to assign an empty variable to embed setImage on discord.js?


I'm aware that setImage must have a value or else it throws an error. Currently, I have the code below.

const imageUrl = "https://media.tenor.com/9OVhj49Ie0sAAAAd/rem-anime.gif";

const embed = new EmbedBuilder()
.setTitle("This is a title")
.setDescription("This is a description")
.setImage(imageUrl)

message.channel.send({embeds: [embed]});

That works fine. But I noticed that if I set the imageUrl variable to an empty string "", it throws an error because it doesn't accept empty value. However, removing the variable on setImage property works even if it still still exist just doesn't have a value i.e. .setImage().

There may be times that imageUrl won't have a link assigned to it. Do I need to wrap the whole embed in an if/else statement like this? Is this the proper approach for this?

const imageUrl = "https://media.tenor.com/9OVhj49Ie0sAAAAd/rem-anime.gif";

if (imageUrl is a link) {
    const embed = new EmbedBuilder()
    .setTitle("This is a title")
    .setDescription("This is a description")
    .setImage(imageUrl)

    message.channel.send({embeds: [embed]});
} else { 
    const embed = new EmbedBuilder()
    .setTitle("This is a title")
    .setDescription("This is a description")
    //removed setImage
    message.channel.send({embeds: [embed]});
}

Solution

  • This is okay now. It should be set to null when there is no url, and I used a ternary operator inside setImage like this.

    imageUrl != "" ? imageUrl : null