Display a book list's reading status in JavaScript
Beginner · 3 min read
Reading apps, to-do lists and online courses all keep a list of items with a done or not-done flag. Somewhere on the screen that flag has to turn into words a person can read, like "already read" or "not read yet".
In this tutorial you will take a list of book objects and turn each one into a readable line. You will also split the list into the books that are read and the ones that are not. You will practise map, filter, template literals and the ? : operator. You need to know what an array and an object are.
An array of objects
Each book is an object with three properties. The whole library is an array of those objects:
const library = [
{ author: 'Bill Gates', title: 'The Road Ahead', readingStatus: true },
{ author: 'Steve Jobs', title: 'Walter Isaacson', readingStatus: true },
{ author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', readingStatus: false },
];
console.log(library[0].title); // The Road Ahead
readingStatus is a boolean: a value that is only ever true or false. Booleans are great for code and bad for people. Nobody wants to read "The Road Ahead: true".
Choosing between two words
The conditional operator condition ? a : b gives a when the condition is true and b when it is false. It is a one-line if:
console.log(true ? 'already read' : 'not read yet'); // already read
console.log(false ? 'already read' : 'not read yet'); // not read yet
Here is the exercise. Try it yourself first if you like, or build it with us step by step.
4 Report the reading status of each book
easyGiven a list of books with author, title and readingStatus, produce a readable line for each one.
Stuck? Three hints, smallest first
- 1.
mapturns each object into a string;joinputs the lines together. - 2. Do not print a raw boolean at a reader. Turn
trueinto words. - 3. Destructuring in the parameter list keeps the callback short.
Step 1: describe one book
Start with a function that turns one book into one line. A template literal is a string in backticks, and ${...} drops a value into it:
const describe = ({ title, author, readingStatus }) =>
`${title} by ${author} \u2014 ${readingStatus ? 'already read' : 'not read yet'}`;
console.log(describe(library[2]).endsWith('not read yet')); // true
Two things to notice. The { title, author, readingStatus } in the brackets is destructuring: it unpacks those three properties into variables as the book comes in, so the body stays short. And \u2014 is the code for an em dash, the long dash. The answer uses it as the separator, because a plain hyphen could be confused with one inside a title.
Print the first book to see the whole line:
console.log(describe(library[0])); // The Road Ahead by Bill Gates, a long dash, then: already read
Step 2: describe every book with map
map calls a function on every item of an array and collects the results in a new array of the same length:
const report = (books) => books.map(describe);
console.log(report(library).length); // 3
console.log(report([])); // []
Passing describe straight to map works because map hands each book to it as the first argument. An empty library gives an empty report, with no special case.
Step 3: print the lines
A for...of loop walks through the array one line at a time:
for (const line of report(library)) console.log(line);
You get three lines, one per book: two that end in "already read" and one that ends in "not read yet". Check that no raw boolean slipped through:
console.log(report(library).some((l) => l.includes('true') || l.includes('false'))); // false
some returns true if at least one line matches. false here means none of them contains the words true or false.
Step 4: split the list in two
filter keeps the items for which your function returns true. Since readingStatus is already a boolean, the function can just return it:
const read = library.filter((b) => b.readingStatus);
const unread = library.filter((b) => !b.readingStatus);
console.log('read:', read.length, ' unread:', unread.length); // read: 2 unread: 1
console.log(read.map((b) => b.title)); // [ 'The Road Ahead', 'Walter Isaacson' ]
! flips a boolean, so the second filter keeps the unread books. Two plus one is three, so every book landed in exactly one group. filter also leaves library alone; it returns a new array.
You may notice the second book's title is a person's name. That is how the data is given, and the code simply prints what it receives.
The full solution
The panel builds the report, prints a line per book, then prints the read and unread counts and the read titles. Press Run to see it.
const library = [
{ author: 'Bill Gates', title: 'The Road Ahead', readingStatus: true },
{ author: 'Steve Jobs', title: 'Walter Isaacson', readingStatus: true },
{ author: 'Suzanne Collins', title: 'Mockingjay: The Final Book of The Hunger Games', readingStatus: false },
];
const describe = ({ title, author, readingStatus }) =>
`${title} by ${author} — ${readingStatus ? 'already read' : 'not read yet'}`;
const report = (books) => books.map(describe);
// Split the list into the two groups.
const read = library.filter((b) => b.readingStatus);
const unread = library.filter((b) => !b.readingStatus);
for (const line of report(library)) console.log(line);
console.log('---');
console.log('read:', read.length, ' unread:', unread.length);
console.log('titles read:', read.map((b) => b.title));
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('there is one line per book', report(library).length, 3);
test('the first line reads properly', report(library)[0], 'The Road Ahead by Bill Gates — already read');
test('an unread book says so', report(library)[2].endsWith('not read yet'), true);
test('no line contains a raw boolean', report(library).some((l) => l.includes('true') || l.includes('false')), false);
test('two books are read', read.length, 2);
test('one is not', unread.length, 1);
test('the groups account for every book', read.length + unread.length, library.length);
test('filtering does not change the source list', library.length, 3);
test('an empty library gives an empty report', report([]), []);
test('every line mentions its title', library.every((b, i) => report(library)[i].includes(b.title)), true);
Nothing subtle here, which makes it a good place to state a rule: never show a raw true or false to a reader. The assertion that no line contains the text "true" enforces it. The em dash in the template is a deliberate separator too — using a plain hyphen would be ambiguous in a title that already contains one.
Common mistakes
- Printing the boolean itself.
${readingStatus}showstrueorfalseto the reader. Turn it into words with? :. - Using
forEachwhen you want a result.forEachreturnsundefined. Usemapto get a new array back. - Forgetting the
!in the unread filter. Without it you get the read books twice.
Try it yourself
- Add a fourth book to
libraryand check the counts change. - Make
describeput "(read)" or "(unread)" at the start of the line instead. - Write
progress(books)that returns text like2 of 3 read.