Short-Term Memory


#1


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");
cashRegister.scan("eggs");
cashRegister.scan("magazine");
cashRegister.scan("magazine");
cashRegister.scan("magazine");

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

This code is correct but I'm trying to understand why when I was closing the add method with a semicolon and then a comma it wasn't working.

I thought you were supposed to close all functions with a semicolon even in objects?


#2

What's the issue you're facing &&/|| error message?


#3


#4

I guess I neglected to look to see if she put inside the backticks.

Thank you :slight_smile:


#5

Semicolons don't go everywhere and anywhere.

It's always best to avoid placing a semicolon after a closing curly bracket.

The semicolon in JavaScript is used to separate statements, but it can be omitted if the statement is followed by a line break (or there’s only one statement in a {block}).

You can read up on it here.


#6

can you answer it? I was only showed what the question was


#7

Yessir

Again, thank you for showing me the question.


#8

Function statements that are declared are hoisted at load time and do not need a semi-colon.

function my_foo(bar) {

}

is a declaration. No semi-colon whether pretty or minified.

var my_bar = function (foo) {

};

is an assignment containing an expression on the right hand side. All assignment statements end with a semi-colon. This is especially the case when the code is minified. (white space removed).

When a function expression is used in an object, it is a member property, therefore a method of the object, and is treated like all members, comma separator.

var my_object = {
    method1: function () {

    },
    method2: function () {

    }
};

It is important to note that expressions in an assignment to do not get hoisted, only their reference variable does. The interpreter needs to be told when to stop parsing, and the seim-colon is what tells it that. That's why the above object ends with one.

The curly brace rule is a loose one and should not be adopted outright. As we've seen above there are at least two cases where the rule does not apply.


#9

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