Snapper
Snapper

Reputation: 29

Statement always true

I have a script where if there is a second argument the script will run else it will run an else statement but even if there is no second argument it will always run the script

if(member && args.slice(1) !== undefined)
  {
    member.kick(args.slice(1).join(' ')).then(() =>{
        message.channel.send("Successfully kicked " + "`" + user.tag + "`" +" for " + "**" +args.slice(1).join(' ') + "**" + " 🙂")
    }).catch(err =>{
        channel.message.send("An unexpected error occured. Logs were sent to the devs")
        console.log(err);
        return;
    });
  }else{
    if(member){
        member.kick().then(() =>{
            message.channel.send("Successfullys kicked " + "`" + user.tag + "`")
            console.log (args[2], args)
        }).catch(err =>{
            channel.message.send("An unexpected error occured. Logs were sent to the devs")
            console.log(err);
            return;
        });

Upvotes: 0

Views: 54

Answers (2)

Donat
Donat

Reputation: 4833

args.slice(1) will never be undefined. If the array args is too short, its result will be the empty array []. This is different from undefined.

Upvotes: 1

Bergi
Bergi

Reputation: 664930

Assuming args is an array, .slice() will always return an array and never undefined. You should check for the length directly:

if (member) {
  const kick = args.length > 1 ? member.kick(args.slice(1).join(' ')) : member.kick(); 
  kick.then(() =>{
    message.channel.send("Successfully kicked " + "`" + user.tag + "`" +" for " + "**" +args.slice(1).join(' ') + "**" + " 🙂")
  }).catch(err =>{
    channel.message.send("An unexpected error occured. Logs were sent to the devs")
    console.log(err);
  });
}

Upvotes: 1

Related Questions