Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi im writing a funciton in JavaScript Define a function viewCart which does not

ID: 3929029 • Letter: H

Question

Hi im writing a funciton in JavaScript

Define a function viewCart which does not accept any arguments. This function should loop over every item in cart to print out "In your cart you have [item and price pairs].". If there isn't anything in your cart, the function should print out "Your shopping cart is empty.".

var cart = [];

function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({item: price});
console.log(item + " has been added to your cart.");
return cart;
}

function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {

var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push(` ${item} at $${price}`)

}
console.log(`In your cart, you have ${newArray}.`);
}
else {
return console.log('Your shopping cart is empty.');
}
}

OUTPUT tells me it cant reach the values of the keys. how do I fix it

Explanation / Answer

var cart = [];

function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({item: price});
console.log(item + " has been added to your cart.");
return cart;
}

function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {

var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push(` ${item} at $${price}`)

}
console.log(`In your cart, you have ${newArray}.`);
}
else {
return console.log('Your shopping cart is empty.');
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote