This forum is now read-only. Please use our new forums at discuss.codecademy.com.

563 points

Submitted by
Rockwell Moon
over 5 years ago

(3:7) item and itemCost

Can someone explain how the item parameter "communicates" with the itemCost parameter?

Here is my code (which passes)...

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

    scan: function (item) {
        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;
        }
        return true;
    }
};

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

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

245 votes

permalink

alt text

  • 0n line 29 we call the scan method from object cashRegister and pass in an item called "eggs"

    • "eggs" gets inserted into the function via the input parameter item which is an interface.
    • For this function call instance, "eggs" becomes the value of variable item.
    • The switch switches the case "eggs" to true, which triggers the function add on line 4 and the value of 0.98 is added to variable total on line 2.

In truth, the program only starts executing at line 29. All the stuff above line 29 is preliminary data that JavaScript will use once it starts running the program. What I mean is that JavaScript scans the program once and it makes an inventory of what is supposed to do. Then, it starts running at line 29 and downward.

2955 points

Submitted by
tony de araujo
over 5 years ago

50 Comments

Rockwell Moon over 5 years ago

Okay, now I think I get it. Thanks for the graphical representation. Was really helpful in trying to wrap my mind around this.

tony de araujo over 5 years ago

You're welcome!

adriansammy over 5 years ago

yeah thanks!

simon John over 5 years ago

why there was no default in switch?

tony de araujo over 5 years ago

default is optional. Do we need default in this program? To do what? do we need an alternative outcome? perhaps an error message or something? The author didn't think so but it is a good question. Just keep in mind that default is optional and only used if you need one.

redbonesflag over 5 years ago

What is the purpose of adding "return true" then? Can that be omitted?

tony de araujo over 5 years ago

In JavaScript that can be omitted. The reason to add a bogus return is to clear the running code out of memory. However, in JavaScript if you don't write an explicit return, an automatic return is provided in the background. The author was probably just following good practices that he has gotten from other languages.

Cullan Luther over 5 years ago

Hey Tony,
I have noticed you have been quite the help on codeacademy, and for that I thank you.

Question:
how can we shorten
cashRegister.scan("eggs"); cashRegister.scan("eggs");
cashRegister.scan("magazine");cashRegister.scan("magazine");cashRegister.scan("magazine"); ?
I have been playing in jshint and I have managed to get the syntax
cashRegister.scan("eggs", "eggs", "eggs"); to work, but obviously this isn't right. How could we say cashRegister.scan("eggs") * 3; ? How can we run the property 3 times in one instance. Not sure if that is how you word it. Excuse my ignorance.

tony de araujo over 5 years ago

Hi Cullan, take a look at this picture. It shows exercise 4/7 and how that is to be accomplished: http://icontemp.com/cc/cahsregsiter_4-7.GIF

Cullan Luther over 5 years ago

ha ha.. I din't know the next lesson did exactly what I was asking. Doh!

Bizmaster28 over 5 years ago

Great explanation!

Dejan over 5 years ago

Tony, are there shorter way for this part of code? cashRegister.scan("eggs");
cashRegister.scan("eggs");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
cashRegister.scan("magazine");

tony de araujo over 5 years ago

There is always a better way since programming is an art. The script will get improved on subsequent exercises. Hopefully that will give you the answer you're looking for. Thanks for your comments fellows!

Tom over 5 years ago

The code could be shortened, but I believe the point of calling scan 5 times is to simulate the scanning of 5 different items at a cash register.

Arseny Mikhalev over 5 years ago

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

Is there any shorter way to print all these out?

tony de araujo over 5 years ago

In the next exercises you will improve the script by multiply the item by the number of units sold.

Arseny Mikhalev over 5 years ago

Thanks, now I got this!

Viggie over 5 years ago

Why the 'return true' at the end of the switch? I dont remember this being in the other switch assignments earlier and my notes have no mention of needing a 'return true'.

More importantly... why on earth are we all of a sudden using a comma instead of a semi-colon at the end of the add function? I assume it has something to do with the order of operations, but it didnt explain this at all and its very confusing.

tony de araujo over 5 years ago

Comma at the end of the function: add is a method which is a property of object cashRegister. The comma serves to separate this property from the next property of the same object. As for a semicolon, only functions assigned to variables get a semicolon at the end. Example: var x = function(){}; (it's just a different syntax style). The return true is outside of the switch, it serves to clear the function add from memory at the end. In JavaScript that is not necessary, the author probably writes extensive code in other languages where return true is a good implementation. You can skip it if you want or better yet, use it for now but don't put too much thought into it. Who knows, it will come to roost someday when you program in a different language and you say "ah, I've seen this implementation before), but I can understand your concern, you want to understand the reason behind it, I think it is just a good practice the author has implemented here but it does not really make a difference when it comes to JavaScript.

tony de araujo over 5 years ago

I meant to clear the function scan from memory.

n0153r about 5 years ago

Thanks for comma explained, that took some nerves :)

GamesCooky about 5 years ago

Hey Tony, are you an admin or moderator or something? Or are you just really good at coding? xd

tony de araujo about 5 years ago

Thanks guys! I'm a moderator. As really good at coding, well, it's all relative, there is always room for improvement which is the reason why I love this activity. :))) When I help out people they also help me out because they make me think about code and it becomes my daily practice.

GamesCooky about 5 years ago

Nice, my dream is to become a video game developer, so that's kinda what i'm aiming for ^^

tmastnner about 5 years ago

same

pmtm23_54c67935e39efe8768005f65_dele about 5 years ago

~COOL!

Ole Kristian Skramstad about 5 years ago

I love you Tony. Finally made sense trough ruberducking my way trough your arrows.

infamousrobby about 5 years ago

Great visual.

Shane about 5 years ago

Thanks Tony

Steve Chang about 5 years ago

WOW. I read most all of your post before it hit me. Totally makes sense now. I too was wondering how the hell the (itemCost) variable was related to anything else in the code.

Marcus about 5 years ago

This explanation is frankly orgasmic, Tony, I am somewhat overwhelmed.

You should be teaching this course with those funky diagrams. It teaches us a lot more than some of these small-bite, step-by-step guides.

Nauryzbai Batyr about 5 years ago

Ote jaqsy tusindirilgen eken! rahmet sagan Tony bratan!

Ben Hawker about 5 years ago

Awesome explanation. Really helped me to understand this concept so much more clearly. Thanks!

Churjumov-Gerasimenko about 5 years ago

Tony, great visualising of this exercise

Sajib Devnath Akash almost 5 years ago

I wanted to know,What does 'return true' do here?

Nikhil Jose almost 5 years ago

Since the object is in Literal notation format, we have to use a comma to close every property. Unlike the Constructor notation, where you use a semi-colon.

Jun Cho almost 5 years ago

This was great, thank you

Eliza Dunaway almost 5 years ago

Yo, best teaching diagram ever- thank you!

SWilliger almost 5 years ago

This is amazing, I only wish this would have been on the main site. it's so much clearer seeing it this way.

jonfreeze almost 5 years ago

Yes, they must use illustrations, all this reading confused the hell out of things.

Robert Besaans almost 5 years ago

Fully agree! This illustration is very clear and informative. The reading is tedious

Francis Ngo almost 5 years ago

i love the illustration visual. sometimes i just need to see the answer rather than read it.

David Ross almost 5 years ago

It's estimated 65% of the population are visual learners. Thanks for this effort in explaining it this way. Amazing help.

David Figiel almost 5 years ago

Thank you for this explanation, it makes it easier to understand.

Jiaxuan512 over 4 years ago

Why put comma after method?

WilliamAnputra over 4 years ago

we have to put comma because it's still inside the literal syntax, and we put comma to add new property

Jiaxuan512 over 4 years ago

thanks

benmarley over 4 years ago

The comma was bugging me, I can't recall learning about this - although there has been a lot to take in. Any idea which lesson this was from? Thanks.

tony de araujo over 4 years ago

yeap, all properties inside of an object need to be separated by a comma except the very last property (which should never have a comma after it). This lesson is a summary of all the previous lessons about objects. The best way to really master it is to go back and repeat the JavaScript lessons a few times over (I don't know of any other way to learn this stuff other than practicing). Thanks again for all the comments!

benmarley over 4 years ago

Thanks, I remembered after posting but I was a bit thrown by the function. You're right, I'm going to go back and work my way through the lessons again now I'm finished. It's a lot to take in at once.


10 votes

permalink

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

scan: function (item) {
    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;
    }
    return true;
}

};

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

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

288 points

Submitted by
Alice Collier
about 5 years ago

6 Comments

David about 5 years ago

I had the exact same code you had! But i missed the comma after the curly bracket :/

Adeyemi Bakare about 5 years ago

guys i think the solution below is better

Vincent Raja almost 5 years ago

Thanks David.. Same Mistake.. :(

dnorthrupvagmail.com almost 5 years ago

Oh wow, that comma was it for me too. I'm not even sure why it's needed....?

dnorthrupvagmail.com almost 5 years ago

Ohhh-I'm stupid. "add" is just another variable in the array as far as JS sees it.

nancyasmina almost 5 years ago

Oh yea, so "add" is a property of the object "CashRegister" - and for this the comma ;-)


2 votes

permalink

The full one:


var cashRegister = {
total: 0,

add: function (itemCost){
this.total += itemCost;
},
scan: function (item) {
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;
    }

return true;

}

}

cashRegister.scan('eggs', 1);
cashRegister.scan('eggs', 1);
cashRegister.scan('magazine', 1);
cashRegister.scan('magazine', 1);
cashRegister.scan('magazine', 1);

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

584 points

Submitted by
Userandname_556c7fb79113cb2677000371
almost 5 years ago

2 Comments

Claudius Rauter almost 5 years ago

*uff yaaah that comma drives me crazy for an hour..

jigmetcodes over 4 years ago

Why did you put 1 in cashRegister.scan('eggs', 1);


1 vote

permalink

What am I missing?
var cashRegister = {
total: 0,
//insert the add method here

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

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

    case "milk": 
        this.add(1.23); 
        break;

    //Add other 2 items here
      case "magazine": 
        this.add(4.99); 
        break;

     case "chocolate": 
        this.add(0.45); 
        break;
    }
    return true;
}

};

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

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

592 points

Submitted by
pythoncoffee
about 5 years ago

11 Comments

tony de araujo about 5 years ago

You last comment was correct ( I made some notes in red on your script). You're also missing a comma.

pythoncoffee about 5 years ago

Tony! Thankyou so much for that and I've just re-read the (why comma) bit above and it's all starting to make total sense! Thanks again buddy! PC

tony de araujo about 5 years ago

You're welcome! Making sense comes in layers, it is definitely a linear process. Enjoy it! :)))

Melvin Chotu about 5 years ago

what about the colon after 'add:'. Why is that needed

tony de araujo about 5 years ago

A delimiter is one or more characters that separates text strings. The colon serves as a delimiter, it separates the key name from its value. Both form one unit, or property of the object they are inside of. add: function(){}; is one unit, add is the label and the rest is the value.

guitarxd about 5 years ago

what's the comma do? do you always write a comma to close a method?

cork411_54728d0d8c1ccc2b5200757c_del about 5 years ago

the second comma is close the add property. a comma is needed to close each property (except for the last property).

PirateGuy_5198db67391dc2e64e0010de_d almost 5 years ago

I though the semicolons closed things?? Why all of a sudden bring in commas to start closing things?

Steve Kanyi almost 5 years ago

when using literal notation to create objects we use commas to separate properties but when we use Constructor notation to create the objects we use semi colon. in our case here we used literal notation the reason why we using comma to separate the add property with scan property of object CashRegister

PirateGuy_5198db67391dc2e64e0010de_d almost 5 years ago

Okay. Thanks Steve.


0 votes

permalink

Ah wait, I think my add function is written wrong. I am writing it as if it is to be used in a constructor right? I should be using it like this maybe...
add: function(itemCost){

P.S.sorry for the confusion

592 points

Submitted by
pythoncoffee
about 5 years ago


0 votes

permalink

var cashRegister = {
total: 0,
//insert the add method here

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

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

    case "milk": 
        this.add(1.23); 
        break;

    //Add other 2 items here
    case "magazine":
        this.add(4.99);
        break;

    case "chocolate":
        this.add(0.45);
        break;

    }
    return true;
}

};

//Scan 2 eggs and 3 magazines
var itemsSelected = ["eggs","eggs","magazine","magazine","magazine"];
for (var i = 0; i < itemsSelected.length; i++){
cashRegister.scan(itemsSelected[i]);
}

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

498 points

Submitted by
Adeyemi Bakare
about 5 years ago


0 votes

permalink

var cashRegister = {
total:0,
lastTransactionAmount:0,
//Dont forget to add your property
add: function(itemCost) {
this.total += itemCost;
lastTransactionAmount=itemCost;
},
scan: function(item,quantity) {
switch (item) {
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
//Add the voidLastTransaction Method here
voidLastTransaction:function(){
this.total-=this.lastTransactionAmount;

},
};

//Void the last transaction and then add 3 instead
cashRegister.voidLastTransaction();
cashRegister.scan("chocolate",3);
cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',1);

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

221 points

Submitted by
Brandon TheHurricane Netzley
almost 5 years ago


0 votes

permalink

with for loop:

var cashRegister = {
total: 0,
//insert the add method here

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

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

    case "milk": 
        this.add(1.23); 
        break;

    //Add other 2 items here
    case "magazine":
        this.add(4.99);
        break;

    case "chocolate":
        this.add(0.45);
        break;
    }
    return true;
}

};

//Scan 2 eggs and 3 magazines
for(i=0;i<2;i++){
cashRegister.scan("eggs");
}
for(x=0;x<3;x++){
cashRegister.scan("magazine");
}
//Show the total bill
console.log('Your bill is '+cashRegister.total);

627 points

Submitted by
Erannatar
almost 5 years ago


0 votes

permalink

var cashRegister = {
    total: 0,
//insert the add method here    
    add: function (itemCost) {
        this.total += itemCost;
    },
    scan: function (item) {
        switch (item) { 
        case "eggs": 
            this.add(0.98); 
            break;

        case "milk": 
            this.add(1.23); 
            break;

        //Add other 2 items here
        case "magazine":
            this.add(4.99);
            break;
        case "chocolate":
            this.add(0.45);
            break;
        }
        return true;
    }
};

//Scan 2 eggs and 3 magazines
cashRegister.scan("eggs");

so, basically when you call the cashRegister.scan("eggs");
the eggs will go to parameter of scan which is item (scan(item))
and with the use of switch somewhere it will became true (or false if not listed in switch);

and if it became true it will enter into that case and trigger

case "eggs":
  this.add(0.98); //which is equal to this  => cashRegister.add(0.98)
  break;

and thus, it will run the function add and pass the price in the total.

584 points

Submitted by
Zirks
almost 5 years ago


0 votes

permalink

Why Comma at the end of the function Add?

399 points

Submitted by
Alejandro De La Rosa
almost 5 years ago

2 Comments

Zirks almost 5 years ago

to continue adding properties to the cashRegister object it's a syntax. So basically the add is a property of cashRegister.

Alejandro De La Rosa almost 5 years ago

Thanks!


0 votes

permalink

hey guys just one question is there a way to improve or better shorten this part?

/Scan 2 eggs and 3 magazines
cashRegister.scan( "eggs" );
cashRegister.scan( "eggs" );
cashRegister.scan( "magazine" );
cashRegister.scan( "magazine" );
cashRegister.scan( "magazine" );

first i was trying something like this: cashRegister.scan( ("eggs")*2 );
this did not worked (because of strings i assume) now i was thinking maybe whit an array and an other function?

From the logic take all items form the array ant take them in to the scan function one by one wich we need a loop for of cause.

make that sense or is there a better, more elegant way of doing this?

280 points

Submitted by
t3321
over 4 years ago

1 Comment

t3321 over 4 years ago

ok i was asking to early next lesson 4/7 describes it :D
modify the scan function can:' function(item,quantity) {
switch (item) {
case "eggs": this.add(0.98*quantity); break;'