A test checks that borrowing a book lowers the number of copies by one. It reads the count, borrows the book and reads the count again. Its report shows the same number twice.
The examples in this track use Shelf, an invented library site. It is not a TestAcademy practice app. Here is the part of the test that keeps the numbers:
let copies = 4;
let before = copies;
copies = copies - 1;
before = copies;
console.log("before: " + before);
console.log("after: " + copies);
before: 3
after: 3
Let's read it one line at a time.
4is a value. A value is one piece of data, such as a number, some text, or true and false.copiesis a variable, which is a name for a value.letcreates the name, and=gives it a value. Read=as "now holds", not as "equals".beforegets the value thatcopiesholds right now, which is 4.copiesnow holds 3.beforestill holds 4, because it received the number and not a link tocopies.- This line is the bug. It gives
beforea new value, so the first reading is lost. console.logprints what you put inside its brackets.beforenow holds 3, so this prints 3.copiesholds 3 as well, so the two lines of the report show the same number.
Nothing warned us on line 4. let allows a name to take a new value at any time.
Protect the first reading with const
const also creates a name. The difference is that a const name can never be given another value.
let copies = 4;
const before = copies;
copies = copies - 1;
console.log("before: " + before);
console.log("after: " + copies);
before: 4
after: 3
before keeps the first reading. copies is still a let, because it has to change.
If someone later adds the bad line again, the code stops:
const before = 4;
before = 3;
TypeError: Assignment to constant variable.
The language guarantees a TypeError here. A TypeError is the error JavaScript raises when a value is used in a way its kind does not allow. The words after it come from the engine. Chrome and Node print this sentence. Firefox and Safari word it differently.
The three kinds of value you meet first
- A number, such as
4or0.5. - A string, which is text inside quotes, such as
"Dune". - A boolean, which is
trueorfalse.
A variable can hold any of them. The name does not record which kind it holds, so copies could later hold "four" and nothing would stop it. The next lecture shows how that causes a wrong total.
In a code review, expect this comment on a let that never changes: "use const". It is more than style. A reader who sees const knows the value on that line is the value everywhere below it.
Remember this
Give every value you want to compare later its own name. Use const unless the value must change. Use let only for the value that changes.
Reference: Declarations in the MDN JavaScript Guide.