JavaGamer
JavaGamer

Reputation: 51

Negating variables in Javascript

I want to make a switch for discord.js, where a mentioned role gets removed when the user already has it, and if he doesn´t have it, it gets attached. So the code here is

let tempRole = message.guild.roles.find("name", args);

            if(message.member.roles.has(tempRole)) {
            console.log(`User has the role`);
        }

args is the array for the command params, like "!role [role name with spaces]" So if I have the role "Test", and I type "!role Test" it outputs "User has the role" so how is the code for the opposite, if the user doesn´t have the role? Because

else if(message.member.roles.has(!tempRole)) {
            console.log(`User has not the role`);
        }

isn´t really working, but the '!' is the only thing i know to negate the result

Upvotes: 0

Views: 320

Answers (1)

J. Pichardo
J. Pichardo

Reputation: 3115

The ! operator negates whatever is found on the right side, in your case you are only negating the tempRole, however what you really want is to negate the result of the has call, like this:

!message.member.roles.has(tempRole)

Nonetheless since there is already an if statement verifying if the user has the role you could just use else

let tempRole = message.guild.roles.find("name", args);

if(message.member.roles.has(tempRole)) {
  console.log(`User has the role`);
} else {
  console.log(`User has not the role`);
}

Or even shorter with the ternary operator

message.member.roler.has(tempRole) 
  ? console.log('User has the role')
  : console.log(`User has not the role`);

Upvotes: 2

Related Questions