How to use if in an if?

I’m trying to do if in an if but when i run it, all of the last 2,3,4 players’ score text pop up instead of the last 2 players’ score text only

let players=2

if (message.content.startsWith("random")) {
        if (players=2) {
          message.channel.send("Last 2 players' score : "+result2+" , "+result1)}
        if (players=3) {
          message.channel.send("Last 3 players' score : "+result3+" , "+result2+" , "+result1)}
        if (players=4) {
          message.channel.send("Last 4 players' score : "+result4+" , "+result3+" , "+result2+" , "+result1)}
3 Likes

You also need an else result for the full function to work.

1 Like

Not so. else is a default, and there is no default for this conditional.

What is missing, though is the closing RBRACE for the outer if.

4 Likes

The problem is actually it consider players=2 always true although the value could be different like 3 or 4
also, i fixed it with else if

if (players=2) {message.channel.send("Last 2 players' score : "+result2+" , "+result1)}
        else if (players=3) {
          message.channel.send("Last 3 players' score : "+result3+" , "+result2+" , "+result1)}
        else if (players=4) {
          message.channel.send("Last 4 players' score : "+result4+" , "+result3+" , "+result2+" , "+result1)}

But still, if the value is 3 or 4, it’s still return with the last 2 players’ score.

1 Like

This is a new model. The problem WAS as stated, as a missing RBRACE. The new code changes up the problem to something else, assuming it is still not working. Don’t mess with us. Focus on the problem you posted with and we can move on from there, else this should be a new topic.

1 Like

The problem is that players = 2, players = 3, and players = 4 are assignments. You are assigning a new value to the variable players in each if-statement.
Assignments evaluate to the value being assigned, so the code you’ve written basically looks like this:

if (2) {}
else if (3) {}
else if (4) {}

All numbers that are not 0 are truthy. In other words, JavaScript evaluates them as true, which means your code always executes every branch of the conditional.

What you want is players == 2 or players === 2.
== and === check for equality. The triple equals is slightly more strict with the rules it uses to determine whether two values are truly equal, but they will both work just fine.

3 Likes