ocean
ocean

Reputation: 11

if runs without checking else if

I'm using node.js with discord.js to create a private chatbot for a server.

I have this code for a command to define who you're at war with.

I get this error if in discord i run "!war" on its own:

TypeError: Cannot read property 'length' of undefined.

What's happened to else if?

if (msg.content.startsWith(prefix + "war")) {
  let [name] = msg.content.split(' ').slice(1);
  if (name.length < 16) {
    war[id[msg.author.id]] = name;
    msg.channel.send("You are now at war with **" + name + "**. Use !pp for war info.");
    console.log("Command executed : !war");
    fs.writeFile('war.json', JSON.stringify(war));
  } else if (name.isNaN) {
    msg.channel.send("Enter something.");
  } else {
    msg.channel.send("Enter something with less than 16 characters.");
  }
}

Upvotes: 1

Views: 48

Answers (2)

Sv Sv
Sv Sv

Reputation: 345

 if (name.length < 16)

It is trying to evaluate name.length and fails here. I suggest you write

  if(name!=undefined && name.length && name.length<16)

Upvotes: 1

Killer Death
Killer Death

Reputation: 451

First check for undefined values and exit function if that is the case, then do some work if input is valid. If is performed before else if in your case so it throws an Exception

Upvotes: 0

Related Questions