4/7 Won't let me pass using best practices?


#1



https://www.codecademy.com/courses/close-the-super-makert/0/4?curriculum_id=506324b3a7dffd00020bf661#


I used a for loop instead of multiplying the quantity against every price (because why...the point of using a program is to save time). My total cost with four of each item was 30.6 (which I checked with a calculator) but I still got the error "Oops, try again. It doesn't seem like your 'quantity' actually works!" My exact output is Your bill is 30.6. My code is below.


var cashRegister = {
    total:0,
    add: function(itemCost){
        this.total += itemCost;
    },
    scan: function(item, quantity) {
        for(var i = 0;
            i < quantity; i++) {
            switch (item) {
                case "eggs":
                    this.add(0.98);
                    break;
                case "milk":
                    this.add(1.23);
                    break;
                case "magazine":
                    this.add(4.99);
                    break;
                case "chocolate":
                    this.add(0.45);
                    break;
            }            
        }
    }
};

// scan each item 4 times

cashRegister.scan("milk", 4);
cashRegister.scan("eggs", 4);
cashRegister.scan("chocolate", 4);
cashRegister.scan("magazine", 4);

//Show the total bill
console.log('Your bill is '+cashRegister.total);

As an experiment I did the bad thing and manually copied and pasted the quantity to multiply against each item price and passed. Do I need to code poorly in order to pass this exercise?


I Have to Scan It More Than Once? (with a For loop)
#2

JS uses floats to represent numbers, and floats are not exact for all values.

If you run into numbers that can't be represented exactly, you'll get something slightly different.. So depending on the order that you do operations on numbers, you may get slightly different results.

The submission test doesn't take this into account, it compares your result to its own, and if they are not exactly the same, it'll say you didn't get it right.

Bottom line: You're safe to do exact comparisons in the range of integers that can be represented and also certain fractional values which can be represented exactly. If you ever stray from that (even as an intermediary result in some math expression), you'll have to treat them as approximations.