I am currently learning javascript and am a litte confused with passing parameters through functions, I was hoping someone could give a clearer explanation
I have the following simple code
//generate random number
var number = Math.round(Math.random()*10 + 1);
//Ask user for name
var playerName = prompt("What is your name?");
//Prompt for intro
var weclome = alert("Hello " + playerName + " Welcome to Guess the Number");
console.log(number);
var playerGuess = prompt("What is your guess ");
if (playerGuess !== null) guess(playerGuess);
function guess(pGuess){
if(pGuess == number) {
alert("Congratulations you have guessed correctly");
} else {
alert("Unlucky, please try again");
}
}
As you can see its ust a simple guess the number game. From what i understand so far I have assigned the variable playerGuess as the result of the input from the prompt, which I pass through the guess function. What I dont understand is that i have called the param pGuess within the guess function. My understanding is that this should not work, but yet it does, how does pGuess know to get its value from playerGuess.
Am I looking at this in totally the wrong way, I would really like to understand this
Thanks
What you’re doing with this line (note the
functionkeyword):is defining a reusable chunk of code (a “function”) which takes a single parameter. When that parameter arrives, it’s accessible by the name
pGuessduring the following block of code, which lasts until the matching}.What you’re doing with this line (note we don’t have the
functionkeyword any more):is calling that function using the current value of the
playerGuessvariable. So you’re passing that value into the function where it places it in the previously definedpGuessvariable for the scope of that function call