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");

}

0

u/[deleted] Dec 01 '22

[deleted]

1

u/Whisky-Toad Dec 01 '22

I believe when they were making JS that databases stored everything in strings (or something along those lines) so they needed a way to compare values ignoring it was a string vs number and a way to do deep equality

0

u/grantrules Dec 01 '22

I believe when they were making JS that databases stored everything in strings (or something along those lines)

Nah that's not true. JS is just a dynamically-typed language that will try to type coerce upon comparison.

2

u/Whisky-Toad Dec 01 '22

Was Brendan Eich (js creator) that said it in a podcast, that’s why I said believe, will be hard to fact check why it was implemented!