Home > Back-end >  Food Menu Javascript
Food Menu Javascript

Time:11-29

I am having a little trouble with this assignment for school. I am using JavaScript to make a menu and give the total price of that order. I am doing 4 menus: Breakfast, Lunch, Dinner, each with sides (Trying to get a little extra credit). I am supposed to use prompt() for this assignment. I was able to get the numbers in an array but I can't get them to equal out anything. I have posted the code I have, but if there is a simpler version I will gladly be doing that too.

I have the menu in HTML and the code itself for the javascript is in the <script> tag.

const b1 = 4;
const b2 = 5;
const bs1 = 2;

const l1 = 10;
const l2 = 20;
const l3 = 5;


const d1 = 10;
const d2 = 20;
const s1 = 2;
const s2 = 3;
const s3 = 5


function orderHere() {
  var i = 0;
  var order;
  sum = 0

  for (i = 0; i < 2; i  ) {
    order = prompt("What would you like to eat today?", "Order Here"   (i   1));
    sum  = order;

  }

  alert("Your price is $"   sum   ". Enjoy your meal!");
}
orderHere();

CodePudding user response:

There is room for improvement but you're off to a good start. To calculate the sum you'll want to put your menu items in a map, which for JavaScript is just an object (there is the built in Map data type but for this assignment the object is fine).

const menu = { b1: 4, b2: 5, ... }

Then when you get a response you can look up the menu item to get it's price and add it's price to the sum.

sum = menu[order]

Just beware that you should never trust user input so be sure to check that the menu item actually exists before trying to add it to the sum.

CodePudding user response:

You could look into javascript maps.

For example:

const prices = new Map();

prices.set("dinner 1", 10);
//The first parameter is the food
//the second is the price

console.log(prices.get("dinner 1")); //returns 10
  • Related