Help this NOOB with a simple javascript question

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.

-wviets

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.

2 Likes

im not 100% familiar with JS syntax but it is good practice to go ahead get in the habbit of allowing Yes/yes/Y/y

"answer === 'y' || answer === 'Y' || answer === "Yes" || answer === "yes" || answer "YES")

the good thing about JS is that you dont have to declare char/ string

but your problem is "=". you are saying answer IS "yes". vs if answer is equal to yes... do this

1 Like

Ah, thank you. I forgot about that.

= : 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.

1 Like

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.

You can check out some examples here

3 Likes