how to make three identical peanut butter and jelly sandwiches in javascript

Here's an example code snippet that creates three identical peanut butter and jelly sandwiches using arrays, loops, functions and strings in JavaScript:

index.tsx
// Define the ingredients of a PB&J sandwich
const bread = "bread";
const peanutButter = "peanut butter";
const jelly = "jelly";

// Define a function for making a sandwich
function makeSandwich() {
  const ingredients = [bread, peanutButter, jelly, bread]; // Order of ingredients in a sandwich
  let sandwich = "";

  // Loop through the ingredients and add them to the sandwich
  for (let i = 0; i < ingredients.length; i++) {
    sandwich += `${ingredients[i]} `;
  }

  return sandwich;
}

// Call the makeSandwich() function three times to create three identical sandwiches
for (let i = 0; i < 3; i++) {
  console.log(`Sandwich ${i + 1}: ${makeSandwich()}`);
}
667 chars
23 lines

This code defines the ingredients of a PB&J sandwich as constants, and then defines a function named makeSandwich()for creating a sandwich. The function returns a string containing the ingredients of a sandwich, in the order they should appear between two slices of bread.

We then use a for loop to call the makeSandwich() function three times, and log the resulting sandwiches to the console.

gistlibby LogSnag