r/learnjavascript • u/Lelouch_5 • Nov 30 '22
Help !!!
Can someone plz tell me , why I am getting errors?
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
2
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
0
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
86
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
42
8
0
-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
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
2
1
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
-1
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
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
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.
1
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.
-26
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
2
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
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
1
2
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
2
u/noobucantbeat Dec 01 '22
As everyone said === or == instead of = but also, write better variable names
2
2
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
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
2
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
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
2
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
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
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
1
1
1
1
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
-1
-1
-2
0
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"
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"True1 === "1"FalseYou 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");}