4. I have to scan it more than once


Hi, I used a for loop with "quantity". It worked, got the right total. But, I guess it wasn't the expected solution. Is there a reason why a for loop should not be used here?

var cashRegister = {
    add: function(itemCost){
        this.total += itemCost;
    scan: function(item, quantity) {
        for (var x = 1; x<=quantity; x++){
            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("eggs", 4);
cashRegister.scan("milk", 4);
cashRegister.scan("magazine", 4);
cashRegister.scan("chocolate", 4);

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


There is only one item passed to the method at a time. The switch statement is able to handle that perfectly well. This is not a suitable scenario for a loop. It adds unneeded code and detracts from readability.

Work through the lessons by staying as close to the instructions as possible for best results. Once you pass, then you are free to go to town with experimentation. But the general rule still applies: simplify, simplify, simplify. Look for ways to shorten the code rather than add to it.


Floats can't represent all numbers and are not appropriate for representing exact results if any intermediary values could not be represented. Integers in the range +-(2^53-1) can be exactly represented by javascript's float type.

Codecademy should not be doing an exact comparison.

A correct implementation would be to store the number of cents instead, and to have controls in place that only allows operations within the range that can be represented.

Trades might not be in whole cents though, and then that falls apart as well, particularly in high speed trading where fractions of cents can really add up.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.