0
var cashRegister = {
    total:0,

    add: function(itemCost){
        total += this.itemCost;
    },

    scan: function(item) {
        switch (item) { 
        case "eggs": 
            this.add(0.98); 
            break;

        case "magazine":
            this.add(4.99);
            break;

        }
        return true;
    }
};

cashRegister.scan("eggs");    
cashRegister.scan("magazines");

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

the output show NAN, and total is undefined. I tried cashRegister.total and this.total in the add method, no luck. What's wrong with the code above?

0

3 Answers 3

3

You have this at wrong place. The line inside add should have been like this

this.total += itemCost;

When you say

total += this.itemCost;
  1. total is not defined yet within the function
  2. this.itemCost means that you are using the element itemCost which is in the current object. But that is actually not there.
Sign up to request clarification or add additional context in comments.

Comments

2

Try this code:

var cashRegister = {
    total:0,

    add: function(itemCost){
        this.total += itemCost;
    },

    scan: function(item) {
        switch (item) { 
        case "eggs": 
            this.add(0.98); 
            break;

        case "magazine":
            this.add(4.99);
            break;

        }
        return true;
    }
};

cashRegister.scan("eggs");    
cashRegister.scan("magazines");

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

Your mistake was at this line:

total += this.itemCost;

Comments

2

Change the add method to:

add: function(itemCost){
    this.total += itemCost; // "this" was in the wrong place
}

Also, you shouldn't ever use floating-point numbers for money - they're not accurate! Use integers as cents instead. Don't convert to dollars until you need to display the dollar amount. Otherwise you might have magical fractions of cents which can add up over time.

var magicDollars = 1.10 + 2.20;
console.log( magicDollars );  // 3.3000000000000003 - Not good! Money can't materialize itself.

var cents = 110 + 220;
var realDollars = cents / 100;
console.log( realDollars );  // 3.3 - Better. No unexpected fractional cents.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.