+ 1

Help me find out why this isn't working (JavaScript)

So I've been trying to create something similar to a game in JavaScript, where it starts off by using a prompt to ask for the player's name. If the player doesn't input a name, I have it ask if they want to use the default name. If they click no, the question is asked again until a name is declared. The code looks something like this: ------------------------------------------------------------------------------------------------------------- function promptname() { var name=prompt("What is your name?"); if (name=name) { sayHello(name); } else { var result=confirm("Would you like to use our default name"); if (result===true) { sayHello("Red"); } else { var name=prompt("Ok then, what is your name?"); if(name=name) { sayHello(name); } else { alert("Ok, let's do this again"); promptname(); } } } } alert("Welcome to the World of Pokemon! I'm Professor Oak! Let's begin!"); promptname(); function sayHello(name) { document.write("Welcome to the world of Pokémon, " + name + " Please choose one of these three starter Pokémon!"); } document.write("hello" + name); ------------------------------------------------------------------------------------------------------------- I put the "document.write("hello" + name);" at the end to test if I could call upon the name variable afterwards, but however I couldn't. I slightly understand that it has to do with the variable name being within the function "promptname", but then the function "sayHello" could use the name variable. Why couldn't "document.write("hello" + name);" call upon this variable? Is there a way to? Thanks in advance.

11th Aug 2018, 6:13 PM
Edwin Lau
Edwin Lau - avatar
2 Answers
+ 1
var name="" function promptname() { name=prompt("What is your name?"); if (name=name) { sayHello(name); } else { var result=confirm("Would you like to use our default name"); if (result===true) { sayHello("Red"); } else { name=prompt("Ok then, what is your name?"); if(name=name) { sayHello(name); } else { alert("Ok, let's do this again"); promptname(); } } } } alert("Welcome to the World of Pokemon! I'm Professor Oak! Let's begin!"); promptname(); function sayHello(x) { document.write("Welcome to the world of Pokémon, " + x + " Please choose one of these three starter Pokémon!"); } document.write("hello " + name); The var name = “” statement outside the function sets ‘name’ as a global variable. Removing the two ‘var’s stops name being reset as a local (inside the function only) variable.
11th Aug 2018, 8:02 PM
Russ
Russ - avatar
0
Thanks you two! I've looked into both global variables and local variables and now I've not only gotten the code to work but I've also learned more about JavaScript variables.
11th Aug 2018, 9:07 PM
Edwin Lau
Edwin Lau - avatar