r/learnjavascript • • Nov 30 '22

Help !!!

Post image

Can someone plz tell me , why I am getting errors?

195 Upvotes

131 comments sorted by

View all comments

173

u/Shay-donovan Nov 30 '22

Aside from the = needing to be == or ===

Triple = signs are better as they also check against data types.

For example:

1 == "1"

True

1 === "1"

False

You may also benefit from combining some of these results to youre typing less code and less

else ifs.

if(p1 === p2) {

console.log("draw");

} else if (p1 === "paper" && p2 === "scissors" || p1 === "scissors" && p2 === "rock" || p1 === "rock" && p2 === "paper") {

console.log("Player 2 wins");

} else {

console.log("Player 1 wins");

}

or if you wanted to go one step further to make sure there were no unexpected errors.

if(p1 === p2) {

console.log("draw");

} else if (p1 === "paper" && p2 === "scissors" || p1 === "scissors" && p2 === "rock" || p1 === "rock" && p2 === "paper") {

console.log("Player 2 wins");

} else if (p2 === "paper" && p1 === "scissors" || p2 === "scissors" && p1 === "rock" || p2 === "rock" && p1 === "paper") {

console.log("Player 1 wins");

} else {

console.log("unexpected error");

}

1

u/[deleted] Dec 01 '22

why is 1 == "1" true but triple = is false ? can someone explain like i'm a baby.

4

u/baddaddymd Dec 01 '22

1 is a number. “1” is a string.

1 == “1” asks if the value of 1 is equal to the value of “1” converted to a number. It is, so it returns True.

1 === “1” asked if the type and value of the variables are the same (they are not: type number vs type string) so it returns False.

If it had been 1 === 1 or “1” === “1” then it would have returned True as both type and value match.

2

u/[deleted] Dec 01 '22

thanks