Just started coding and im stuck on a lesson?

Joined
Oct 30, 2022
Messages
1
Reaction score
0
1.In script.js, create a new variable at the top of the file named groceryList and set it to an array of strings,
"Bananas", "Milk", "Eggs", and "Bacon"

2.Create a second variable named message and set its initial value to the String,
"Please pick up the following from the store: "

3.After you've created the two variables, create a loop that will loop through every item in the groceryList array.

4.Inside the loop, use string concatenation to add each item within the grocery list to the end of the message, separated by commas.

5.The final grocery item should not have a comma at the end.

6.You will need to use an if statement to conditionally add the comma after each item.
You should concatenate each grocery item and the comma as two separate steps.

(Hint: You can determine if an individual grocery item is the last item in the array by comparing its index (i) to the length of the array. If the index is equal to the array's length minus one, it is the last item.)

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Result: After the loop, log the final message to the browser console. It should read:

"Please pick up the following from the store: Bananas, Milk, Eggs, Bacon"

I'v got to number 4 but have no clue where to go from there???
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
JavaScript:
const groceryList = ['Bananas', 'Milk', 'Eggs', 'Bacon'];
   let message = 'Please pick up the following from the store: ';
  
   for(let i=0; i < groceryList.length; i++){
   message += groceryList[i];
   if(i < groceryList.length - 1){
   message += ', ';
   }
   }
  
   console.log(message);
  
   /* We can shorten this code as below */
   console.log(message + groceryList.join(', '));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,717
Messages
2,569,382
Members
44,701
Latest member
OurCBDLifeSupplement

Latest Threads

Top