r/learnjavascript • • Nov 30 '22

Help !!!

Post image

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

195 Upvotes

131 comments sorted by

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

}

41

u/Lelouch_5 Nov 30 '22

Ty ☺️

30

u/Shay-donovan Nov 30 '22

My pleasure! I am currently in the middle of a JavaScript bootcamp I bought on Udemy myself. I have had some previous experience but wanted to deep dive. I'm still not 100% confident and still have a long way to go. However helping others helps me learn as well! Its a win win. So thank you as well! :)

8

u/Wooden_Yesterday1718 Dec 01 '22

Highly recommend using parentheses to separate these sets of conditions even if they’ll technically operate as expected regardless.

1

u/Number_2_Dad Dec 01 '22

Can you give an example of this? I'm trying to pick up as many tips possible as a noob

1

u/Wooden_Yesterday1718 Dec 01 '22

Sure! I just mean like if there’s a complicated set of conditions you should organize it to be readable and therefore maintainable: (this && this && this) || (this && this) || this. Sometimes these parentheses don’t change the logic because they still work when evaluated in order (my example NEEDS the parentheses, though). But even if they will work without, it is a million times easier to manage if you are intentional with stuff like that from the start.

6

u/ObiFlanKenobi Dec 01 '22

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

Elon would fire you on the spot.

3

u/Shay-donovan Dec 02 '22

Not enough code! Haha

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

0

u/[deleted] Dec 01 '22

[deleted]

13

u/Steve_OH Dec 01 '22

As someone who knows some c, a lot of c++, it’s nice to be able to compare data without having them match 100% since some data comes from an external source and the looser comparison makes this easier. Having === is a nice solution imo to being strict when you want and loose when you need to.

0

u/[deleted] Dec 01 '22

[deleted]

1

u/noXi0uz Dec 01 '22

in actual, non-beginner projects, you will only see === everywhere, most often even enforced by a linter. Some people make an exception when they want to concisely check for both null or undefined:
if (x != null)

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!

1

u/finger_milk Dec 01 '22

I think it's amazing that it doesn't care about type. Because we know both of these are the same in almost all cases.

1

u/coconutfrosting Dec 01 '22

console.log(true + true);

19

u/Smilinkite Nov 30 '22

Well, you'll get far less squigly lines if you replace every = with ==. Starting line 4.

8

u/Lelouch_5 Nov 30 '22

Ty ☺️ . I really forgot about the equality operator.

16

u/xroalx Nov 30 '22

Even better if you use the === operator. It won't try to convert stuff from one type to another.

3

u/gtrman571 Nov 30 '22

If you know the types being compared are going to be the same then == and === do literally the exact same thing.

2

u/noXi0uz Dec 01 '22

yeah but it's best to create a habit of always using === so you avoid forgetting it in scenarios where it matters.

1

u/____0____0____ Dec 01 '22

Sure, but in almost any professional context where they care about quality, == would be disallowed from a linter and === would be allowed. It's not worth it from a readability standpoint of having to read a == and try to figure out whether it's context dictates it should be a == or ===. You should always have === for equality check unless you really know what you're doing.

5

u/revanyo Nov 30 '22

In the future when you see the squiggly error it means something is wrong with your code and usually your IDE will tell you a hint of sorts. This will ensure that you are not making 101 mistakes.

If you are not seeing any of the squiggly lines and the code runs but with odd results then that means the code runs but not in the way you want it to, and those are the times that reaching out on reddit or stack overflow will be helpful.

3

u/dankscience Nov 30 '22

It’s a common mistake. Don’t get discouraged. I hope you keep coding!

2

u/kriskoeh Nov 30 '22

It’s okay. 💕

2

u/Darthcolo Dec 01 '22

As a general rule, try to investigate why there is a squiggly line on your code. Where is the first one? Why is it there? What is it highlighting? Comment the rest of the code, and try again. Change something until the error disappears, then reintroduce the code bit by bit.

Software developers spend 35-50 percent of their time validating and debugging software. The cost of debugging, testing, and verification is estimated to account for 50-75 percent of the total budget of software development projects, amounting to more than $100 billion annually. Source

3

u/FirstRock5 Nov 30 '22

Doesn’t visual studio no tell you that if you hover over the first =?

2

u/Lelouch_5 Nov 30 '22

I was trying to solve some problems on code wars and got the error. So to check what the error was I copy pasted it on VS code.

421

u/GrismundGames Nov 30 '22

Awwwww...those were the days.

Go get 'em!

31

u/GrismundGames Dec 01 '22

I couldn't get my very first "Hello World" html file to run for two hours.

I posted it in my boot camp's Slack chanel and they were like,

"Dude... You called your file index..html."

🤦‍♂️

87

u/throwawaysomeway Nov 30 '22

lmao for real. This is where people either diverge from coding or continue onwards with a potential career. some of my students miss the most basic syntax stuff that just blows my mind. some people are not meant to code I feel. Not to say OP is one of them, but you get what I mean.

1

u/asguardia Dec 01 '22

I want to jump back on coding. I have made a few games on Java, one in Unity and another one in UE. However I fear that I may have forgotten everything. Where to begin?

1

u/throwawaysomeway Dec 01 '22

Depends on what you are trying to achieve. Game dev? Web dev? etc.

1

u/asguardia Dec 01 '22

Game dev!

1

u/throwawaysomeway Dec 01 '22

Game dev is definitely not an easy task but doable. I found that learning full stack development helped a ton with my understanding. Unity has free courses that wonderful people in the industry I know have recommended. I would start there for sure, if you don't mind using unity. Unity is a solid engine though, you can really achieve just about anything with it these days.

2

u/asguardia Dec 01 '22

Sweet, thank you.

0

u/[deleted] Nov 30 '22

[deleted]

4

u/Shy-pooper Dec 01 '22

I disagree. Anecdote: Started with electronics 2 years ago and now launched this the other day: https://loodio.com

Generally, people vastly overestimate other people.

Same feeling when you read those tech emails between the big corporate leaders like Musk, Jobs etc.

I’ve met so many people in my life that could have had those positions with a little encouragement.

3

u/dark_salad Dec 01 '22

Username checks out.

Seriously though, I've never understood why bathroom fans market themselves with how quiet they are. That's literally the opposite of what most people want. Nice product.

3

u/Shy-pooper Dec 01 '22

You are absolutely right. Thank you!

86

u/CATASTROPHEWA1TRESS Nov 30 '22

I love that it’s a photo of the screen, such desperation

120

u/AliFurkanY Nov 30 '22

use === instead of =

-43

u/javier123454321 Dec 01 '22 edited Dec 01 '22

Probably should go with ==== just to be sure \s

8

u/Barnezhilton Dec 01 '22

Or just use:

!!=

2

u/SteadfastPooper Dec 01 '22

Not not equal, this is if a politician wrote code.

0

u/SteadfastPooper Dec 01 '22

I think you will find ================= is production grade

-9

u/its_a_gibibyte Dec 01 '22

Is 4 better than 3? Why not ==========? Make sure those values are really equal to each other.

38

u/morasyid Nov 30 '22

remember,

= is to assign a value

== is to compare value

=== is to compare value AND type

13

u/aguyfromhere helpful Dec 01 '22

Not quite. == will coerce and then compare value.

4

u/IlooklikeAshKetchum Dec 01 '22

Sorry but what's coerce mean?

11

u/cant_have_nicethings Dec 01 '22

To change a type based on a bunch of complicated logic that is best ignored. In production code based you rarely see double equals. It’s avoided because it’s confusing and unintuitive.

3

u/unknown_ally Dec 01 '22

It’s the price you pay for not explicitly declaring variable types! An extra = !

1

u/[deleted] Dec 01 '22

OOH the humanity!

1

u/godprobe Dec 01 '22 edited Dec 01 '22

The docs state it about as simply as I might've:

https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion

(In case you're just not familiar with the word "coerce", it's almost the same as the word "force" in this context. A number is coerced/forced to be a string, for example.)

33

u/agdolusannbierts Nov 30 '22

Could do just one draw with (p1 === p2) I think

6

u/aguyfromhere helpful Dec 01 '22

I’d also suggest OP learn to use a loop to test this. There will be some conditions in the loop that mean you can just break out early. Be a good next step in understanding coding and data structures.

47

u/DGCA Dec 01 '22

IMO, a lookup table would be even cleaner. E.g.

const winnerToLoserMap = {
  rock: 'scissors',
  paper: 'rock',
  scissors: 'paper',
};

function rps(p1, p2) {
  if (p1 === p2) {
    console.log('Draw!');
    return;
  }

  if (winnerToLoserMap[p1] === p2) {
    console.log('Player 1 won!');
  } else {
    console.log('Player 2 won!');
  }
}

2

u/JawnStaymoose Dec 01 '22

This is my move…. For many things. Feels so much cleaner and digestible.

2

u/cardyet Dec 01 '22

That's really nice!

1

u/[deleted] Dec 01 '22

What are the benefits of this approach over writing out the conditions? I’m guessing readability and less chance of error, but is it faster in any way?

3

u/DGCA Dec 01 '22

Ditto what /u/Kavinci said, but I wanna stress that the main benefit is the readability. "Is it any faster?" can be an important question, but it usually isn't.

2

u/Kavinci Dec 01 '22

Yeah, a lookup table is faster than if conditions. For a small dataset like this the speed is negligible but it really shines with larger datasets.

1

u/97b21a651a14 Dec 01 '22

Loved this. It's so readable!

-1

u/[deleted] Dec 01 '22 edited Dec 01 '22
const OPTIONS = ['rock', 'scissors', 'paper']
const beats = (p1, p2) => OPTIONS.indexOf(p1) === (OPTIONS.indexOf(p2) + 1) % OPTIONS.length
const rps = (p1, p2) => beats(p1, p2) ? 'Player 1 wins' : beats(p2, p1) ? 'Player 2 wins' : 'Draw'  

Sorry for the nested ternary lol

1

u/Macaframa Dec 01 '22

This gives me a huge headache to look at.

1

u/DGCA Dec 01 '22

If this one doesn't give you a migraine, I failed:

function rps(p1, p2) {
  const options = ['rock', 'scissors', 'paper'];
  const winner = options
    .map((_, x, arr) => {
        return arr.map((_, y) => (((3 - y) % 3) + x) % 3)
    })[options.indexOf(p2)][options.indexOf(p1)];

  return winner ? `Player ${winner} wins!` : 'Draw';
}

2

u/Macaframa Dec 01 '22

This one should hurt the most

const rps = (p1, p2, options = ['rock', 'scissors', 'paper']) => options.map((_, x, arr) => arr.map((_, y) => (((3 - y) % 3) + x) % 3))[options.indexOf(p2)][options.indexOf(p1)] ? `Player${options.map((_, x, arr) => arr.map((_, y) => (((3 - y) % 3) + x) % 3))[options.indexOf(p2)][options.indexOf(p1)]} wins!` : 'Draw!';

1

u/DGCA Dec 01 '22

Using a default argument instead of declaring a variable 👏

1

u/Macaframa Dec 02 '22

Honestly if the logic is sound and you stuff this away in some file and import this, it ain’t half bad. But if you’re going to do that, you might as well make it more readable so it can be worked on

1

u/[deleted] Dec 01 '22

:(

1

u/DGCA Dec 01 '22

Haha, I thought it was interesting in a code golf sense. Using an item's position in an array to hold actual data is both clever and cursed.

1

u/[deleted] Dec 01 '22

This approach is however offer more generalizable. E.g. introducing some new options: Rock beats scissors beats paper beats stick beats whatever ... beats rock.

https://en.wikipedia.org/wiki/Circular_buffer

1

u/DGCA Dec 02 '22

Scope creeping rock paper scissors, eh?

1

u/Macaframa Dec 02 '22

It would take any engineer time and effort to have to read, let alone understand what’s happening here before they can make any changes. From a production quality standpoint it’s not up to snuff. You’re creating technical debt that someone will eventually shave to refactor.

15

u/Macaframa Dec 01 '22
const rps = (p1, p2) => {
    const RESULT_MAP = {
        'scissors': {
            'paper': 'Player 1 won!',
            'rock': 'Player 2 won!',
            'scissors': 'Draw!',
        },
        'rock': {
            'scissors': 'Player 1 won!',
            'paper': 'Player 2 won!',
            'rock': 'Draw!',
        },
        'paper': {
            'scissors': 'Player 2 won!',
            'rock': 'Player 1 won!',
            'paper': 'Draw!',
        }
    }
    console.log(RESULTS_MAP[p1][p2])
}

this is a cute way of doing it.

3

u/longknives Dec 01 '22

I don’t think you would need quotes around any of the key names like this.

1

u/Macaframa Dec 01 '22

It’s true. But then again, we wouldn’t do anything like this to begin with

2

u/Kavinci Dec 01 '22

I was thinking this too.

5

u/prog_aimer Dec 01 '22

Switch case... Please!

1

u/Stranded_In_A_Desert Dec 01 '22

They’ll get there. Switches were slightly harder to wrap my head around when I first started learning.

6

u/anonymousICT Nov 30 '22

You should try a switch statement

2

u/aguyfromhere helpful Dec 01 '22

I’d suggest a loop.

2

u/ThunderySleep Dec 01 '22

My first assumption was this post was taking a crack at them for not using a switch, before seeing the operator issue.

2

u/[deleted] Dec 01 '22

Switch and case! Switch and case! And break;

1

u/ray_zhor Dec 01 '22

Try a modulus operator

2

u/tacticalpotatopeeler Nov 30 '22

Assignment vs equality.

Also formatting…

Hover your mouse over the squiggly lines and you’ll get a little window that tells you an error message.

Single = no longer means what it used to mean in math. Takes some getting used to. You’ll get there!

2

u/delventhalz Nov 30 '22

Did you mouse over the red squigglies? What did they say?

1

u/butt_soap Dec 01 '22

They say don't press print screen

2

u/noobucantbeat Dec 01 '22

As everyone said === or == instead of = but also, write better variable names

2

u/eighty_twenty Dec 01 '22

yes

2

u/eighty_twenty Dec 01 '22

But also, Assignment = Equivalent == Is ===

2

u/[deleted] Dec 01 '22

It would make me extremely happy if OP would select lines 6-12 and press SHIFT + TAB. ;)

2

u/peter-s Dec 01 '22 edited Dec 01 '22

An exercise in brevity (which does not account for malformed input):

const opts = ["rock", "paper", "scissors"]

function rps(p1, p2) {
  const beatsP1 = opts[Math.abs((opts.indexOf(p1) + 1) % opts.length)]
  console.log(`${p1 === p2 ? "Nobody" : p2 === beatsP1 ? "P2" : "P1"} wins!`)
}

4

u/fungusbabe Dec 01 '22

This makes my head hurt. Why not just use a lookup table??

Readable code >>> snappy one liners

2

u/peter-s Dec 01 '22

Because I was performing an exercise in brevity.

2

u/fungusbabe Dec 01 '22

Oh lol well in that case very nicely done

2

u/JRutter3 Dec 01 '22
a = 1  // set a equal to 1
a == 1 // a is equal to 1?
a === 1 // a is 1. 1 is a. They are 1.

2

u/bodefuceta92 Dec 01 '22

Oh god, why am I laughing so hard 😂

2

u/[deleted] Dec 01 '22 edited Dec 01 '22

Missing else statement, is what I see at first glance. Now after actually looking at the code from troubleshooting POV, it seems the error is occurring due to the operator you're using.
'=' is an assignment operator.
As you want to compare whether the value on the left is equal to the value on the right, you should use '=='. Or at best '===' if you wish to ensure that the datatype as well matches.
Other than that use the && || operators to shorten your code. Try to DRY as much as possible.

2

u/Charlie669 helpful Dec 01 '22

You need only check if the values are different or equal to one another, otherwise one of the players wins. Think about that.

2

u/Moosupply Dec 01 '22

let random = Math.floor(Math.random() * 3)

if(random === 0) {

random === "rock"

} else if(random === 1) {

random === "paper"

} else {

random === "scissors"

}

function rps(user, computer){

if(user === computer) {

return "it's a tie"

} else if(user === "rock" && computer === "scissors") {

return "you win!"

} else if(user === "paper" && computer === "rock") {

return "you win!"

} else if(user === "scissors" && computer === "paper") {

return "you win!"

} else {

return "you lose!"

}

}

console.log(rps(0, random))

2

u/Brompy Dec 01 '22

Would a Switch statement be better here instead of all the else ifs?

2

u/iamthesexdragon Dec 01 '22

You're using an assignment operator. That's different from the equality operator. = is for assignment and == or === are for checking equality. == causes type coercion, === is strict when it comes to comparing so it doesn't coerce types.

2

u/finixanthony Dec 01 '22

Stop listening to music while codin

2

u/[deleted] Dec 01 '22

==, not = op

2

u/SteadfastPooper Dec 01 '22

= means your assigning the right hand side to the left hand side, i.e x = 2, x then becomes 2, whereas you need == or === (equality operator or strict equality operator) as you are checking X is equal to Y, not assigning Y to X.

2

u/[deleted] Dec 01 '22

Focus on strict comparison (===) rather than the assignment operation (=)

2

u/goosemano82 Dec 01 '22

The root cause of your confusion stem from continuing to code while you have errors. The instant you see a red squiggly error underlining: stop everything you are doing, hover to see the error message, research it, and fix it.

Otherwise you are deviating farther and farther from the solution as you go.

2

u/TalkCoinGames Dec 01 '22

== instead of just =.

if(p1== ....

3

u/Positive_Ebb9204 Nov 30 '22

You are assigning a value to the variable which is not possible when using if else checks. You need to use “===“ instead

3

u/dreadpirateloki Dec 01 '22 edited Dec 01 '22

Here's another way to code it up if you are interested:

const MOVES = {
    ROCK: 0,
    PAPER: 1,
    SCISSORS: 2,
}

const rps = (a,b) => {
    if (a === b) return "Tie"
    return ((a - b + 3) % 3 === 1) ? "Player 1 Wins" : "Player 2 Wins"
}

console.log(rps(MOVES.ROCK, MOVES.PAPER))

edit: Forgot that in javascript -2%3 !== 1 and cleaned up code a bit.

2

u/longknives Dec 01 '22

This is clever, but doesn’t seem to work? Rock vs scissors is (0 - 2) % 3 or (2 - 0) % 3, which work out to -2 and 2 respectively, neither of which is 1, so the function reports a tie instead of player 1 winning.

1

u/dreadpirateloki Dec 01 '22

Ha, good catch, you are right. I'm used to python where -2 % 3 actually becomes 1.

1

u/David-8094 Dec 01 '22

Put ==== between parenthesis

1

u/Southern-Estimate-58 Dec 01 '22

Why you didn't give space before && logical operator?

1

u/bozdoz Dec 01 '22

Hover over the red squiggles

1

u/Zoroae Dec 18 '22

Just... switch...

1

u/girl-InTheSwing Dec 01 '22 edited Dec 01 '22
// Map of all possible game outcomes
const outcomes = new Map(
  [
    [ 'rock-rock', 'Draw!'],
    [ 'paper-paper', 'Draw!'],
    [ 'scissors-scissors', 'Draw!'],
    [ 'rock-scissors', 'Player 1 won!'],
    [ 'paper-rock', 'Player 1 won!'],
    [ 'scissors-paper', 'Player 1 won!'],
    [ 'rock-paper', 'Player 2 won!'],
    [ 'paper-scissors', 'Player 2 won!'],
    [ 'scissors-rock','Player 2 won!']
  ]
)

/**
 * Rock Paper Scissors game outcome
 * @param p1 {string} Player 1 selection
 * @param p2 {string} Player 2 selection
 */
const rps = (p1, p2) => {
  // create key for game outcome
  const game = [p1,p2].join( '-');
  // determine outcome by looking it up
  console.log( outcomes.get(game) ?? 'Unknown game');
}

rps(  'scissors', 'paper');

rps( 'paper', 'scissors');

rps( 'fred', 'paper');

0

u/Hail42 Dec 01 '22

Looks like a 🪵

-1

u/badassmexican Dec 01 '22

Missing ; after the console.log lines

-2

u/bodefuceta92 Dec 01 '22

What about the legendary =====operator

0

u/[deleted] Dec 01 '22

[deleted]

2

u/haikusbot Dec 01 '22

Um you do see the

Red squiggly lines right? That's where

Your issues are lol

- techgirl8


I detect haikus. And sometimes, successfully. Learn more about me.

Opt out of replies: "haikusbot opt out" | Delete my comment: "haikusbot delete"