Console
In Node.js we often need to determine what actions a program is taking. We can use console.log
, along with some other methods, to print out messages.
The console.log
method can receive multiple arguments, and it can even perform substitutions for arguments. With assert meanwhile we can tell if a necessary condition is true.
This program uses the console.log
method in a variety of ways. It prints out the values of 2 constants in the program: animal and number.
string
.console.log
—the values are all printed in a single line.string
literals, a string
and a number to the console. A newline is automatically added on the end.String
interpolation syntax, with the backtick char
, can be used to create a string
that is then passed to console.log
.const animal = "bird"; const number = "10"; // Part 1: use substitution format. console.log("animal: %s number: %d", animal, number); // Part 2: write 2 values to the console. console.log("animal:", animal); // Part 3: write 4 values to the console. console.log("animal:", animal, "number:", number); // Part 4: use string interpolation to write a string to the console. console.log(`animal: ${animal} number: ${number}`);animal: bird number: 10 animal: bird animal: bird number: 10 animal: bird number: 10
Suppose we have a function that needs to always have a certain condition be true—an argument must not be null
, for example. With assert, we can print a message if an expression is false.
// Step 1: assert passes if the condition is true, and nothing is written. var number = 10; console.assert(number === 10, "Number must be 10!"); // Step 2: assert fails. number = 5; console.assert(number === 10, "(ASSERT 2) Number must be 10!")Assertion failed: (ASSERT 2) Number must be 10!
Count
How often is a certain value encountered at a point in a program? With console.count
we can determine this with minimal additional code.
// Use count to keep track of a count at a key. console.count("a"); console.count("a"); // This count is 1. console.count("b"); // This will increase count for this key to 3. console.count("a");a: 1 a: 2 b: 1 a: 3
Though it is not essential to a program's functionality, many Node programs use console.log
output. With log, assert and count, we can understand the actions a program takes.