I started learning my first programming language yesterday. I'm taking "Foundations of Programming: the Fundamentals" on lynda.com. Poison of choice: javascript.
I'm trying to practice stuff that I learned so I wrote this script.
var name = prompt("What is your name?");
alert("Hello, " + name);
alert("Let's play a game");
var answer1 = prompt("Can you use a sword? (yes/no)");
if (answer1 = "yes") {
alert("YAY!");
}
else {
alert("Aww....");
}
When I go through the prompts on the web interface, the last alert always says "YAY!", no matter what I type in the last prompt.
So tell me how I need to rewrite the first condition in the if statement so that it understands the yes input.
If you dont want to run that in a browser you could always run it with node to display the output in a terminal like a normal language.
also the if statement should be
if(answer1==="yes")
Just one = is an assignment statement to the variable answer1, two ==, dont quote me on this checks the pointer reference and === checks the string for equality.
= : assignment operator == : evaluation (is this equal to) === : evaluation (is this equal to and of same type)
You are comparing the value of strings so you will need the ===, if you just used the == then the JIT would be like "yep those are both strings, I'll return true', when what you actually want to do is compare the strings values as well.
This isn't quite true. == considers value and NOT the type. For example: '5' == 5 would return true. === evaluates value AND type which would make 5 === '5' false. comparing two strings with == will always return false if the values are different.