0

I am trying to generate a name. Why won't this code work?

var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"]; var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"]; function createName(toVariable) { var name = names[Math.floor(Math.random() * names.length)]; var surname = surnames[Math.floor(Math.random() * surnames.length)]; toVariable = name + " " + surname; } var botName = ""; createName(botName); console.log(botName);

7th Apr 2019, 8:57 PM
D Oakahn
D Oakahn - avatar
2 odpowiedzi
0
Because when you insert the botName variable as an argument into the createName function. You are actually passing it's value, not the variable itself. Things like this are made by returning the output of the function. var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"]; var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"]; function createName() { var name = names[Math.floor(Math.random() * names.length)]; var surname = surnames[Math.floor(Math.random() * surnames.length)]; return name + " " + surname; } botName = createName() console.log(botName);
7th Apr 2019, 9:23 PM
Toni Isotalo
Toni Isotalo - avatar
0
var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"]; var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"]; function createName() { var name = names[Math.floor(Math.random() * names.length)]; var surname = surnames[Math.floor(Math.random() * surnames.length)]; return name + " " + surname; } var botName = createName(); console.log(botName); You don't need to send argument to function. Sending string variable to this function is just copying variable by value. But if you take an object (reference type) it will work: function createName(person) { var name = names[Math.floor(Math.random() * names.length)]; var surname = surnames[Math.floor(Math.random() * surnames.length)]; person.name = name + " " + surname; } var botName = {}; createName(botName); console.log(botName.name);
7th Apr 2019, 9:26 PM
Владимир Землянушкин
Владимир Землянушкин - avatar