1
var user = prompt("what is your name?");
if (user == "joe")  {
  var game = "what's up joe"
}
if (user == "alex") {
  var game = "hello alex how are you"
}
else {
  game = "sorry don't know you"
}

var other = alert(game);

For some reason this does not work I want to make game be equal to a number of different things. If I use more than 3 if statements game is always equal to the last one. Could someone please help me?

jwodder
  • 54,758
  • 12
  • 108
  • 124
Joseph Clark
  • 39
  • 1
  • 7

3 Answers3

3

Declare "game" outside the if statement an use it inside.

var user = prompt("what is your         name?");
var game = "";
if (user == "joe")  {
  game = "what's up joe"
} else if (user == "alex") {
  game = "hello alex how are you"
} else {
  game = "sorry don't know you"
}

var other = alert(game);
cycopepe
  • 531
  • 8
  • 21
1

You can't: No such thing as block scope in JavaScript.

And probably the best article on the topic: JavaScript Scoping and Hoisting.

Community
  • 1
  • 1
Vidul
  • 10,128
  • 2
  • 18
  • 20
0

var user = prompt("What is your Name?");
var auth = "joe";
if (user == auth) {
  alert("Whats Up ")+ user;
};
else if(user != auth | user!=="alex"){
  alert("I dont Know you! ")+ user;
};
else {
  alert("Error!");
};
Quatban Taco
  • 310
  • 1
  • 15