0

I am writing a dice game, similar to risk. This is not the entirety of the code, just the function asking for the players name.

function getPlayerNames(p1, p2, p3, p4){
    p1 = prompt("What is Player 1's name?", '');p1;
    p2 = prompt("What is Player 2's name?", '');p2;
    p3 = prompt("What is Player 3's name?", '');p3;
    p4 = prompt("What is Player 4's name?", '');p4;
    return;
}

let player1Name, player2Name, player3Name, player4Name;
getPlayerNames(player1Name, player2Name, player3Name, player4Name);

when player(1,2,3,4)Name is used later in the code it shows as 'undefined'. What is wrong that it is not declaring the names as they are typed in the prompt, and showing that they are undefined?

John V
  • 5
  • 6

1 Answers1

1

As said in the comments: JS does not pass by reference, it pass by value

Said that, here's a possible solution to you:
1. Get the names inside the function.
2. Return an array with the names.
3. Assign the names to variables.

Suggestion: Also read about Variable Scopes

function getPlayerNames(){
    let p1 = prompt("What is Player 1's name?", '');
    let p2 = prompt("What is Player 2's name?", '');
    let p3 = prompt("What is Player 3's name?", '');
    let p4 = prompt("What is Player 4's name?", '');
    return [p1,p2,p3,p4];
}

var names = getPlayerNames();    
let player1 = names[0],
player2 = names[1],
player3 = names[2],
player4 = names[3];

console.log("Player 1: " + player1);
console.log("Player 2: " + player2);
console.log("Player 3: " + player3);
console.log("Player 4: " + player4);
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48