Bot doesn't go over switch case properly | Discord.js v12

Viewed 61

I am going over my discord bot trying to refactor my code a little and I have this switch case which works perfectly with if/else but it doesn't run in the switch. Any ideas why? I tried a lot of things but I can't get it to work... I am also pretty sure it is a dumb mistake I am doing.. The case in question is the "self" case that is not running. So in normal circumstance it would be

if (getTag == self) {
   // code
}

Here is the code. Thanks in advance!

var getTag = message.mentions.users.first(); 
var self = message.author.id;
switch (getTag) {
    case undefined: 
        // sample
        break;
    case self:
        // sample
        break;
    case client.user: 
        // sample 
        break;
    default: 
        // sample
        break;
}
2 Answers

message.mentions.users.first() returns a User object. It means, you can't simply compare it to other objects or strings.

Your first case, undefined will work, because message.mentions.users.first() returns undefined if there are no mentions.

The second one won't work, because you try to compare an object to a string (a user ID).

The third one won't work either as you're trying to compare a User object to another User object.

Try to only compare its id property or even better, get rid of the switch statement and use if statements instead:

const getTag = message.mentions.users.first();
const self = message.author;

if (!getTag) {
  // same as case: undefined
  return;
}

if (getTag.id === self.id) {
  // same as case: self
  return;
}

if (getTag.id === client.user.id) {
// same as case: client.user
  return;
}

// same as default case

You compare an User Object with a User ID so you need to change the getTag to the following code:

var getTag = message.mentions.users.first() ? message.mentions.users.first().id : undefined; 
Related