JavaScript, inside out · Chapter 1 of 51

Hello, console

By the end of this chapter you can make a program tell you what it is doing: print a line, raise a warning, show a list as a table, count how often something happens and time how long it takes. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: First day at Tapri
  • 5 tasks
  • JavaScript
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Ravi wants to see what the new ordering app is doing: a line for every new order, a warning when an item runs low, the menu at a glance, how often the order bell rings, and how long the 4 pm rush really takes.

A program works in silence. It can add up a bill or check the stock, and unless it says something, you never see the answer or even know that it ran. So before menus or payments, you learn how to make code speak: the console.

The lesson

Printing a line

console.log prints whatever you give it. Give it several values, separated by commas, and it prints them on one line with a space between each. The + sign glues two pieces of text together with no space, so there you add the spaces yourself:

console.log('Rider', 'Sunita', 'is out with', 3, 'orders');
console.log('Milk:' + 'Nandini');
console.log('Milk: ' + 'Nandini', '(' + 12 + ' litres)');
Rider Sunita is out with 3 orders
Milk:Nandini
Milk: Nandini (12 litres)

Text goes in quotes, numbers do not. To try an example, type node in the terminal, paste a line and press Enter (ignore the undefined Node prints after it).

Warnings and errors

console.warn is for "this looks wrong, keep an eye on it", and console.error is for "this is broken":

console.warn('Milk is late:', 20, 'minutes');
console.error('UPI machine is offline');
Milk is late: 20 minutes
UPI machine is offline

They print like log, but are marked as a warning and an error, so tools can pick them out (a browser colours them yellow and red). The check reads the warnings, and a warning printed with log is not one.

Lists as tables

console.table draws a list of objects as rows and columns. Give it a second value, an array of column names, and it shows only those:

const riders = [
  { name: 'Imran', area: 'Domlur', phone: '98450 11223' },
  { name: 'Sunita', area: 'Koramangala', phone: '98450 44556' },
];
console.table(riders, ['name', 'area']);
┌─────────┬──────────┬───────────────┐
│ (index) │ name     │ area          │
├─────────┼──────────┼───────────────┤
│ 0       │ 'Imran'  │ 'Domlur'      │
│ 1       │ 'Sunita' │ 'Koramangala' │
└─────────┴──────────┴───────────────┘

The column names must be in an array. Pass a single name as plain text, console.table(riders, 'name'), and Node refuses:

TypeError [ERR_INVALID_ARG_TYPE]: The "properties" argument must be an instance of Array. Received type string ('name')

Counting and timing

console.count(label) keeps one counter per label and prints it on every call. Another label (even one with a capital letter) is another counter, and with no label it counts under default:

console.count('door');
console.count('phone');
console.count('door');
console.count();
door: 1
phone: 1
door: 2
default: 1

console.time(label) starts a stopwatch and console.timeEnd(label) stops it and prints how long it ran. The time changes on every run:

console.time('boil');
console.log('Milk on the stove');
console.timeEnd('boil');
Milk on the stove
boil: 0.381ms

The two labels must match exactly. Stop 'Boil' after starting 'boil' and nothing is timed; Node prints a warning instead:

(node:103) Warning: No such label 'Boil' for console.timeEnd()

Where your code goes

Each task in exercise.js is a function with its first line written. The names in brackets are its parameters: on each call they hold the values it was called with. The check calls your functions with its own values, so use the parameters:

function welcome(name) {
  console.log('Welcome to Tapri,', name);
}
welcome('Sunita');
welcome('Imran');
Welcome to Tapri, Sunita
Welcome to Tapri, Imran

return hands a value back to the caller and ends the function. const keeps a value under a name (more in chapter 2):

function cupsLeft(made, sold) {
  return made - sold;
}
const left = cupsLeft(50, 38);
console.log('Cups left:', left);
Cups left: 12

if runs its block only when its test is true. < means less than, >= means greater than or equal to (chapter 17 covers if):

const litres = 3;
if (litres < 5) {
  console.warn('Milk is low:', litres, 'litres');
}
Milk is low: 3 litres

A parameter can even hold a function. If job holds one, job() runs it and gives back whatever it returns.

Your turn

Your five tasks are at the top, all in exercise.js, one function each, written in place of each throw line. The check reads every detail: the exact words and spaces, which console method printed them, the labels order bell and rush hour, and that 10 left is not low.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    logOrder: one line for each new order

    Write logOrder(customer, item). It prints one line with console.log, exactly like Order: masala chai for Ravi when it is called with Ravi and masala chai: the word Order and a colon, the item, the word for, then the customer, with one space between each part. Use exactly one console.log call, and return nothing.

    Careful with the order: the customer comes first in the brackets, but last in the line.

  2. Task 2

    warnLowStock: warn when an item runs low

    Write warnLowStock(item, left). When fewer than 10 are left, print a warning with console.warn, exactly like Low stock: ginger (4 left), and return true. When 10 or more are left, print nothing and return false.

    10 left is not low: it gives false and no warning. Use console.warn, not console.log, because the check reads the warnings.

  3. Task 3

    showMenu: the menu as a two-column table

    Write showMenu(menu). It prints the menu it is given with one console.table call that shows only two columns: name, then price. Hand console.table the menu itself, as it is (the check looks for the very same array), and the column names as an array. Return nothing.

  4. Task 4

    ringBell: count every ring of the bell

    Write ringBell(). Every call counts one ring with console.count under the label order bell, exactly that text, all lower case, so the console shows order bell: 1, then order bell: 2. Return nothing.

  5. Task 5

    timeRush: time the rush and keep its result

    Write timeRush(work). work is a function. Start a timer with console.time under the label rush hour, run work exactly once, stop the timer with console.timeEnd under the same label, and return whatever work returned.

    The timer must start before work runs and stop after it finishes.

What you will learn

  • console.log, console.warn and console.error: print a line, a warning or an error.
  • console.table: show a list of objects as rows and columns, with only the columns you pick.
  • console.count and console.time: count how often a line runs, and time how long some work takes.
  • The functions in exercise.js: where your code goes, and how a function hands back an answer.

More in First day at Tapri

Build "Hello, console" yourself

Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.