Why do I get an unexpected identifier?
my code:
let raceNumber = Math.floor(Math.random() * 1000);
let early = false;
let age = 18;
if age += true && early = true
Im on the race day project
Why do I get an unexpected identifier?
my code:
let raceNumber = Math.floor(Math.random() * 1000);
let early = false;
let age = 18;
if age += true && early = true
Im on the race day project
this line:
if age += true && early = true
could you explain to me how you think this line of code works?
if they both equal true. checking if they both are true
first, the general syntax for if
is the following:
if (condition) {
// code to execute
}
in your case, all the brackets are missing. and +=
(incremental assignment) and =
(assignment) are not comparison/equality operators.
How do I make it so if they are both true it changes the variable raceNumber by 1000. Heres what I did
let raceNumber = Math.floor(Math.random() * 1000);
let early = false;
let age = 18;
if(true) {
age && early
let raceNumber = raceNumber + 1000
}
And this error,
/home/ccuser/workspace/learn-javascript-U2P2/main.js:6
let raceNumber = raceNumber + 1000
^
ReferenceError: raceNumber is not defined
at Object. (/home/ccuser/workspace/learn-javascript-U2P2/main.js:6:21)
@css4466983849 When referencing a variable for the second time, i.e. to change it, you do not need have let again. See the example below:
let variable1 = 3 //Here, I have declared the variable for the first time, so I *do* need *let*.
variable1 = 4//Here, because I have already declared a variable called 'variable1' , I do not need the let keyword. Same goes for const, or, in pre-ES6, var.
Then, for ifโฆelse, you need, at least for the age, a condition saying age is equal to 18. In JavaScript you can write it like this:
let variable = 2
const otherVariable = true
if (variable === 2 && otherVariable) { /* notice how there is the three equal signs (===)? This means
//code here equal to. You can also write otherVariable === true.*/
}
In your case, you need to have the equal signs for age. There are other operators as well:
โ!==โ is not equal to
โ>=โ is greater than or equal to
โ<=โ is less than or equal to
โ>โ is greater than
โ<โ is less than
I hope that made some sense to you!
Well actually, a const variable cannot be reassigned.
const pet = 'dog'
pet = 'cat' // should give an error
This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.