Short-term memory - Getting this error "ReferenceError: total is not defined"


3. Short-term Memory
Write the add method which has a single parameter, itemCost. It will add the itemCost to the total.
We have partially written the scan method for you and started a switch statement. Add the following 2 items to the switch statement:
"magazine", 4.99
"chocolate", 0.45
Finally, use the scan method to buy "eggs" twice and a "magazine" three times.

I checked my code, everything seems right but i keep getting that error - "ReferenceError: total is not defined"
I need help

var cashRegister = {
    total: 0,
//insert the add method here    
add: function(itemCost)
total += itemCost;
    scan: function (item) {
        switch (item) { 
        case "eggs": 
        case "milk": 
        //Add other 2 items here
        case "magazine":
        case "chocolate":
        return true;


//Scan 2 eggs and 3 magazines
for (i=0;i<2;i++){

for (i=0;i<3;i++) {
//Show the total bill
console.log('Your bill is ';


The above is looking up the scope chain to a global variable that does not exist.

The variable that does exist is in the context of an owner object, so when a method accesses it, it looks to the this object to find it. += ...



total += itemCost;

total is a member variable, to access member variables we need to this.memberVariableName


Oh!! Thanks, I changed it to += itemCost;

Works :slight_smile:


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