Calling a Function - returns "[Function : X]"

Me again!

I have created a function but it’s not returning as I’d expect.

So I have created a random message generator - created some arrays and got it to randomly select indices, the purpose of the function is to combine them.

//The following are arrays in which the different random values will come from const countries = ['England', 'Italy', 'France']; const capitals = ['London', 'Rome', 'Paris']; const leaders = ['Boris Johnson', 'Sergio Mattarella', 'Emmanuel Macron']; //Select a random index let randomCountry = Math.floor(Math.random() * countries.length); let randomCapital = Math.floor(Math.random() * capitals.length); let randomLeader = Math.floor(Math.random() * leaders.length); //Individuals let country; let capital; let leader; //Switch statements to define each index switch (randomCountry) { case 0: country = 'England'; break; case 1: country = 'Italy'; break; case 2: country = 'France'; }; switch (randomCapital) { case 0: capital = 'London'; break; case 1: capital = 'Rome'; break; case 2: capital = 'Paris'; break; }; switch (randomLeader) { case 0: leader = 'Boris Johnson'; break; case 1: leader = 'Sergio Mattarella'; break; case 2: leader = 'Emmanuel Macron'; break; }; const randomMsg = () => { console.log( `${capital} is the capital city of ${country}. The head of state there is ${leader}!` ) }; console.log(randomMsg);

Hi Ben,

I assume that you want to log the right capital and prime minister for each country that is randomly chosen, right?
You could achieve that with a nested array, for example:

const facts = [['Great Britain', 'Boris Johnson', 'London'], ['France', 'Emmanuel Macron', 'Paris']];

Then you could display the facts like this:

console.log( `${arr[2]} is the capital city of ${arr[0]}. The head of state there is ${arr[1]}!`

Then you would just need one function that generates a random value based on the length of the facts array and pass the array with the data of one country as an argument to the function randomMsg.
No need for the switch cases then, as well.

Oh, and to your initial question: You haven’t invoked your function. That’s why the console logs the function itself – not the value.

1 Like

Hi,

Thanks for coming back to me. :slight_smile:

I’m actually trying to get a random combination of a country, a capital city and a head of state into the returned string. So it could end up being completely wrong, but that’s fine.

Is the code I’ve got close or?

Thanks again!

Ben.

Oh, ok!
Yes then you’re close. You just need to make that function call an actual function call.
There are more concise ways of doing this, for example you don’t need the switch cases for that either, but from what I see it should work.

1 Like