Variable Problems


#1


https://www.codecademy.com/courses/javascript-beginner-en-NhsaT/2/5?curriculum_id=506324b3a7dffd00020bf661

Is there a way when you assign a variable to a number, when you put it in an if phrase to not have the number replaced by the variable? I want the console to say correct if you enter 574, but the 574 is replaced by firstAddition, and the firstAddition variable is replaced by 574 if you type it into the prompt, still resulting into the console showing wrong.(Sorry the wording's weird)


var firstAddition = prompt("Let's start easy. What's 192+382?"); {
    if(574===firstAddition)
        console.log("Correct");
    else console.log("Wrong.");
};


#2

To get this right you can not override a number. So this won't work:

754 = "text";

It'll just produce an invalid left-hand side assignment error.
But the problem with your code is different anyway. It is that you use prompt and prompt returns a string. So even if you enter 574 it will store "574". Now here you can use the difference between == and === because:

== compares values so 574 == "574" will work

but

=== compares values and types so although 574 == "574" works the test whether "string" == "number" will fail.

So one option to make it work would be to use the lesser equal ==. Or to convert your prompt to a number using parseInt("574",10) to make it a number (parseFloat accordingly if it is a float).


#3

Thanks for helping me with this problem! I was really stumped on it :smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.