You put ';' after the last element of the property list in first object. Fix it:
var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost) {
this.total += itemCost;
this.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;
},
voidLastTransaction: function() {
this.lastTransactionAmount -= this.total;
}
};
The fix is in the line I commented with '
// was invalid ';' after '}'
'.
That's all.
There is one trick to find out errors in lexical level of the code, which won't be normally caught as exception.
Take the text and put it in some string, same, the variable named
code
:
var code = "var a = {a:1, b:2;}";
try {
eval(code);
} catch(e) {
alert(e);
}
To better locate the exception and fix it, you can use such properties of the exception object as
fileName
,
stack
,
fileName
and
lineNumber
(unfortunately, not in all browsers),
name
and
message
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error[
^].
As you can see, you can also output the name of the error
constructor
, which would show you how your error is classified:
EvalError
,
InternalError
, …,
TypeError
,
URIError
. However, normally it should be shown in the property
name
.
This can be called "converting lexical errors in to exceptions". :-)
This trick will allow you to deal with the code you develop with the convenience more typical to compiled languages. Note that JavaScript is not a primitive pure-interpretive language working line by line. Its interpretation does have rudimentary "compilation" phase at the very beginning.
—SA