This program works identically to the one you just wrote, but it has been organized differently because some functions return a value instead of logging them to the console.

Do This

Read the code for this program
Finish the code for the randomCompliment function. Use the comments and the code for randomGreeting to help.

greetAndCompliment("Benjamin");
greetAndCompliment("Raji");
greetAndCompliment("Esmerelda");

function greetAndCompliment(name){
console.log(randomGreeting() + name);
console.log(name + randomCompliment());
}

// Generates a random greeting
// return {string} - random greeting, followed by a comma and space
function randomGreeting(){

var greetings = ["Good day, ", "Bonne journée, ", "Buenos dias, ", "Magandang araw, ", "美好的一天, "];
var randomGreet = greetings[randomNumber(0, greetings.length-1)];
return randomGreet;

}

// Generates a random compliment
// return {string} - random compliment, followed by exclamation point
function randomCompliment(){
var compliments = [", you have incredible hair!", ", you are astonishingly smart!",
", your fashion sense is unmatched!", ", your smile lights up the room!",
", you are uncommonly talented!", ", you are ridiculously funny!"];
// Write code to complete this function

}

1 answer

To complete the randomCompliment function, you will want to choose a random compliment from the compliments array and return it. Similar to how the randomGreeting function works, you will use the randomNumber function to select a random index from the compliments array.

Here's the completed code for the randomCompliment function:

function randomCompliment(){
  var compliments = [", you have incredible hair!", ", you are astonishingly smart!", 
                     ", your fashion sense is unmatched!", ", your smile lights up the room!", 
                     ", you are uncommonly talented!", ", you are ridiculously funny!"];
  
  var randomCompliment = compliments[randomNumber(0, compliments.length - 1)];
  return randomCompliment;
}

This function generates a random index using the randomNumber function, retrieves the compliment at that index from the compliments array, and then returns it. Now, when you call greetAndCompliment, it will display a random compliment each time.

Make sure that the randomNumber function is defined elsewhere in your code, as this function will need it to work properly. Here's an example of what the randomNumber function might look like:

// Generates a random number between min and max (inclusive)
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

With these pieces in place, your program should now fully function, providing both a random greeting and a random compliment for each name passed to greetAndCompliment.