reference.js:2
console.log(scor);
^
ReferenceError: scor is not defined
at Object.<anonymous> (reference.js:2:13)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Console
14.2 The three errors you will meet most
You used a name that JavaScript does not know, as above. The cause is almost always a typo, a variable used outside its scope (Chapter 10), or something used before it was created.
type.js:2
console.log(user.name);
^
TypeError: Cannot read properties of undefined (reading 'name')
at Object.<anonymous> (type.js:2:18)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Console
This is the most common error in all of JavaScript. You tried to read name from undefined, which has no properties. In real programs, user is undefined because a find found nothing, a server returned no data, or a property name was misspelled. The question to ask is: “why is this value undefined, when I expected an object?”
syntax.js:1
const prices = [10, 20, 30;
^
SyntaxError: Unexpected token ';'
at wrapSafe (node:internal/modules/cjs/loader:1713:18)
at Module._compile (node:internal/modules/cjs/loader:1755:20)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Console
14.3 Stack traces: how did we get here?
In bigger programs, functions call functions that call other functions. When an error happens deep inside, Node.js prints a stack trace: the path of calls that led to the error.
functiongetCity(user){returnuser.address.city;}functionwelcome(user){return`Hello from ${getCity(user)}!`;}console.log(welcome({name:"Sara"}));
Recorded output$ node stack.js
stack.js:2
return user.address.city;
^
TypeError: Cannot read properties of undefined (reading 'city')
at getCity (stack.js:2:23)
at welcome (stack.js:6:24)
at Object.<anonymous> (stack.js:9:13)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Console
14.4 Bugs without errors
The hardest bugs do not produce any error. The program runs and gives the wrong answer:
// The average of 10, 20 and 30 should be 20…functionaverage(numbers){lettotal=0;for(leti=1;i<numbers.length;i++){total=total+numbers[i];}returntotal/numbers.length;}console.log(average([10,20,30]));
Recorded output$ node average-bug.js
16.666666666666668
Console
No red text, but 16.67 is not 20. When nothing tells you where the problem is, you make the program tell you. The simplest tool is console.log: print the values you are unsure about, at the moments you are unsure about them.
i = 1 number = 20 total = 0
i = 2 number = 30 total = 20
final total: 50
16.666666666666668
Console
Now the bug is obvious: the loop starts at i = 1, so it never adds the first number, 10. The total is 50 instead of 60. This is the trace table from Chapter 2, written by the computer. Fix the cause, here by using for…of, which cannot skip the first item, and test again, including an unusual case:
Now the bug is obvious: the loop starts at i = 1, so it never adds the first number, 10. The total is 50 instead of 60. This is the trace table from Chapter 2, written by the computer. Fix the cause, here by using for…of, which cannot skip the first item, and test again, including an unusual case:
constcart=[{name:"Book",price:25,quantity:1},{name:"Sticker",price:3,quantity:2},];console.log("Items in cart:",cart.length);console.table(cart);console.error("Something is wrong here!");
The program crashes before it prints anything. Read the error message and fix it with a single character.
You will practise: reading an error message from top to bottom: the line, the caret, the type and the description.
Steps
Find the type of error. A ReferenceError means “I do not know this name”.
Find the line and the caret ^: they point at the exact name JavaScript could not find.
Compare that name, letter by letter, with the variable you created at the top. JavaScript is case-sensitive.
Fix it, run the program again, and make sure the output below appears.
Hint: most errors you will ever meet are typos. Your editor can help: when you click on a variable, it highlights every place with the same name. A name that does not light up is a typo.
greet-bug.js:9
console.log(welcome(firstname, visits));
^
ReferenceError: firstname is not defined
at Object.<anonymous> (greet-bug.js:9:21)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
No error at all, but the total is nonsense. Find the two bugs hiding in five lines.
You will practise: bugs without errors, tracing values with console.log, the difference between text and numbers, and off-by-one loops.
Steps
Read the wrong total carefully. Numbers stuck together like 01204535 are a clue: something is joining text, not adding numbers.
Add console.log(i, list[i], typeof list[i]) inside the loop and run again.
Bug 1: the prices are strings, so + glues them. Convert each one with Number(…).
Bug 2: the last line of your trace shows i equal to 3 and the value undefined. The array has no item 3. Change <= to <.
Remove your console.log lines, run once more, and check the result by hand: 120 + 45 + 35 = 200.
Hint:NaN (“not a number”) spreads like a stain: any sum that touches it becomes NaN. When you see it, look for the first undefined or text that went into a calculation.
// Prices arrive as text, as they do from a form or a fileconstprices=["120","45","35"];constdiscount=20;functiontotal(list){letsum=0;for(leti=0;i<=list.length;i++){sum=sum+list[i];}returnsum;}constbefore=total(prices);console.log("Total:",before);console.log("After discount:",before-discount);
// Prices arrive as text, as they do from a form or a fileconstprices=["120","45","35"];constdiscount=20;functiontotal(list){letsum=0;for(leti=0;i<list.length;i++){sum=sum+Number(list[i]);}returnsum;}constbefore=total(prices);console.log("Total:",before);console.log("After discount:",before-discount);
Recorded output$ node cart-fixed.js
Total: 200
After discount: 180
Console
Project 14.3 · Challenge
The order that breaks the list
The first order prints, then the program dies. Follow the stack trace back to the cause, and fix it so every order prints.
You will practise: reading a stack trace, finding bad data rather than bad code, and guarding against missing values.
Steps
Read the stack from the top: the crash is in label, which was called by printAll, which was called from line 17.
The message says it could not read name of undefined. So in order.customer.name, the undefined is order.customer.
One order printed before the crash, so the problem is the second order. Look at the data: order 2 has no customer.
Decide what should happen. Here a missing customer is a guest, so add an if (!order.customer) at the start of label and return a “guest” line.
Run again. All three orders should print, and the program should finish normally.
Hint: the line that crashes is often not the line that is wrong. The code in label was fine; the data was not what it expected. Real data from users and servers is always missing something, so professionals check before they read deep inside an object.
#1 Omar: 40
orders-bug.js:8
return `#${order.id} ${order.customer.name}: ${order.total}`;
^
TypeError: Cannot read properties of undefined (reading 'name')
at label (orders-bug.js:8:41)
at printAll (orders-bug.js:13:17)
at Object.<anonymous> (orders-bug.js:17:1)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Each line below has one bug. Predict the error type, then check with Node: console.log("hi), const a = 1; a = 2;, let list; list.push(1);, consol.log(5);
The book's short answer
SyntaxError, TypeError (assignment to a constant), TypeError (list is undefined), ReferenceError.
// Each snippet has one bug. Our predictions are in the comments; the program runs each one and prints the real error.// vm runs a piece of code given as text, so one error does not stop the whole program.constvm=require("node:vm");constsnippets=[['console.log("hi)',"SyntaxError"],// the closing quote is missing["const a = 1; a = 2;","TypeError"],// a const cannot be given a new value["let list; list.push(1);","TypeError"],// list is undefined, and undefined has no push["consol.log(5);","ReferenceError"],// no variable is called consol];for(const[code,predicted]ofsnippets){try{vm.runInNewContext(code,{console});console.log(`${code} -> no error`);}catch(error){constmark=error.name===predicted?"✓":"✗";console.log(`${mark}${code} -> ${error.name}: ${error.message}`);}}
Recorded output$ node predict-errors.js
✓ console.log("hi) -> SyntaxError: Invalid or unexpected token
✓ const a = 1; a = 2; -> TypeError: Assignment to constant variable.
✓ let list; list.push(1); -> TypeError: Cannot read properties of undefined (reading 'push')
✓ consol.log(5); -> ReferenceError: consol is not defined
Exercise 14.2 · Easy
Fix stack.js in two ways: by giving the user an address, and by making getCity return "somewhere" when there is no address.
The book's short answer
Add address: { city: "Alexandria" } to the user, or write return user.address ? user.address.city : "somewhere";
// Fix 1: give the user an address.functiongetCity(user){returnuser.address.city;}functionwelcome(user){return`Hello from ${getCity(user)}!`;}console.log(welcome({name:"Sara",address:{city:"Alexandria"}}));// Fix 2: getCity copes with a user who has no address.functiongetCitySafely(user){returnuser.address?user.address.city:"somewhere";}functionwelcomeSafely(user){return`Hello from ${getCitySafely(user)}!`;}console.log(welcomeSafely({name:"Sara"}));console.log(welcomeSafely({name:"Adam",address:{city:"Gaza"}}));// The short way to write the same thing, with ?. (optional chaining) and ??:console.log(({name:"Huda"}).address?.city??"somewhere");
Recorded output$ node stack-fixed.js
Hello from Alexandria!
Hello from somewhere!
Hello from Gaza!
somewhere
Console
Exercise 14.3 · Medium
Put a breakpoint inside addToCart in the shop from Chapter 12. Click “Add to cart” and step through the function, watching cart change.
The book's short answer
Click the line number inside addToCart in the Sources panel, click the button on the page, and use Step.
Show the solution
Open shop.html in the browser and open DevTools (F12), then the Sources panel.
In shop.js, click the line number of the first line inside addToCart. A blue marker appears: that is the breakpoint. (In this copy, the line debugger; does the same job, so you can skip this step.)
Click "Add to cart" on any product. The page freezes and the line is highlighted.
In the Scope pane, open cart: it is still empty on the first click.
Press Step over (F10) line by line. After cart.push(...), cart has one item; on a second click on the same product, line.quantity++ runs instead.
constcatalog=[{id:1,name:"Code from Zero",price:25},{id:2,name:"Bit mug",price:8},{id:3,name:"Bit sticker",price:3},{id:4,name:"Bit T-shirt",price:15},];constcart=[];// Draw one card per productfunctionrenderProducts(){constcontainer=document.querySelector("#products");for(constproductofcatalog){constcard=document.createElement("article");card.className="card";constname=document.createElement("h3");name.textContent=product.name;constprice=document.createElement("p");price.textContent=`$${product.price}`;constbutton=document.createElement("button");button.textContent="Add to cart";button.addEventListener("click",()=>addToCart(product.id));card.append(name,price,button);container.append(card);}}functionaddToCart(productId){// With DevTools open, the browser pauses here, as if you had clicked this line number in the Sources panel.// Hover over cart to see its value, then press "Step over" (F10) line by line and watch it change.debugger;constline=cart.find((item)=>item.productId===productId);if(line){line.quantity++;}else{cart.push({productId,quantity:1});}renderCart();}// Redraw the cart from the data every time it changesfunctionrenderCart(){constlist=document.querySelector("#cart-lines");list.replaceChildren();lettotal=0;for(constitemofcart){constproduct=catalog.find((p)=>p.id===item.productId);constlineTotal=product.price*item.quantity;total+=lineTotal;constli=document.createElement("li");li.textContent=`${product.name} × ${item.quantity}`;constamount=document.createElement("span");amount.textContent=`$${lineTotal}`;li.append(amount);list.append(li);}document.querySelector("#cart-total").textContent=cart.length===0?"Your cart is empty.":`Total: $${total}`;}renderProducts();renderCart();
Exercise 14.4 · Medium
This function should count the words longer than three letters, but returns the wrong number. Find the bug with console.log: function count(words) { let n = 0; for (const w of words) { if (w.length > 3) n = 1; } return n; }
constwords=["code","is","fun","and","useful","always"];// The buggy version, with a labelled console.log inside the loop.functioncountBuggy(list){letn=0;for(constwoflist){if(w.length>3)n=1;console.log(` w = "${w}", n = ${n}`);}returnn;}console.log(`Buggy: ${countBuggy(words)}`);// The log shows n stuck at 1 after "code", "useful" and "always": n = 1 sets it, it never adds.functioncount(list){letn=0;for(constwoflist){if(w.length>3)n++;// the fix: add 1 each time}returnn;}console.log(`Fixed: ${count(words)}`);
Recorded output$ node count-words.js
w = "code", n = 1
w = "is", n = 1
w = "fun", n = 1
w = "and", n = 1
w = "useful", n = 1
w = "always", n = 1
Buggy: 1
Fixed: 3
Console
Exercise 14.5 · Challenge
Take a program from an earlier chapter that works. Ask a friend to add one small bug without telling you where. Find it using only the method in Section 14.6, and write down each step you took.
The book's short answer
There is no single answer; the important part is writing down each step of the method.
Show the solution
Bug hunt log
The program: queue-with-bug.js, a copy of queue.js from Chapter 9 with one bug added by a friend. I followed the method of Section 14.6 and wrote down each step.
Reproduce it.node queue-with-bug.js prints Total: 50 every time. Working by hand: 10 + 6 + 0 + 6 + 10 + 10 + 0 = 42.
Read the error. There is no error message: the program runs, but the answer is wrong. It is a bug without an error (Section 14.4), so the next tool is console.log.
Form a guess. 50 is 8 more than 42. Two visitors, aged 9 and 70, should pay 6 each; if they both paid 10, the total would be exactly 4 + 4 = 8 more. My guess: the child and senior rule never matches.
Test the guess.queue-traced.js prints each age with its price, without changing the logic. Ages 9 and 70 get 10, and every other price is right, so the guess is confirmed: the bug is in that one condition.
Fix the cause. The condition says age < 13 && age >= 65: younger than 13 and at least 65 at the same time, which no one is. The rule needs ||. queue-fixed.js prints 42. Unusual cases checked: ages 12, 13, 64 and 65.
// Step 4 of the method: test the guess with labelled console.log lines, without changing the logic.constqueue=[34,9,2,70,16,41,3];lettotal=0;for(constageofqueue){letprice;if(age<4){price=0;}elseif(age<13&&age>=65){price=6;}else{price=10;}console.log(`age = ${age}, price = ${price}`);total=total+price;}console.log(`Total: ${total}`);
Recorded output$ node queue-traced.js
age = 34, price = 10
age = 9, price = 10
age = 2, price = 0
age = 70, price = 10
age = 16, price = 10
age = 41, price = 10
age = 3, price = 0
Total: 50
// A friend added one bug to queue.js from Chapter 9. The total should be 42; the program prints 50.constqueue=[34,9,2,70,16,41,3];lettotal=0;letfreeTickets=0;for(constageofqueue){letprice;if(age<4){price=0;freeTickets++;}elseif(age<13&&age>=65){price=6;}else{price=10;}total=total+price;}console.log(`Free tickets: ${freeTickets}`);console.log(`Total: ${total}`);