Node.js
console methods
Learn console.log, console.error and console.table.
console methods
The console object has many methods beyond console.log. console.error writes to the standard error stream (stderr); console.warn is for warnings; console.info for informational messages.
console.table(data) prints an array or object in tabular form; with column headers it is easier to read. console.time("label") and console.timeEnd("label") measure elapsed time in milliseconds; useful for performance comparisons. console.group and console.groupEnd organize messages into indented groups. Choosing the right method makes output more readable; if errors go to stderr, log systems can capture them separately.
Measuring with console.time
To measure how long an operation takes, use console.time and console.timeEnd. Both take the same label; when the labels match, the elapsed time is printed.
Example: console.time("loop"); for (let i = 0; i < 1000; i++) {} console.timeEnd("loop");. Output: loop: 0.123ms. The time is in milliseconds; small differences are visible. Multiple time calls with the same label each keep a separate counter. This is practical for comparing algorithms or finding a slow loop. We are learning console.time here, not performance.now from a later lesson; this one is accurate enough.
Exercise Log a record with console.log
Define const record = { name: "Ayşe", age: 30 };. Start with console.log("Console started"). Print the record with console.log("Record: " + record.name + ", age: " + record.age). End with console.log("Console ended").
Show example solution
const record = { name: "Ayşe", age: 30 };
console.log("Console started");
console.log("Record: " + record.name + ", age: " + record.age);
console.log("Console ended");
Test yourself
-
Match each method to its purpose
- console.log
- General output
- console.error
- Error stream
- console.table
- Tabular format
- console.time
- Measures time
-
Where does console.error write?
console.error("Hata")
- Only to a file
- Nowhere
- To the standard error stream (stderr)
- To standard output (stdout)
Show answer
To the standard error stream (stderr) — console.error writes to stderr.
-
Complete the console.table call
console.____(kullanicilar);
Show answer
console.table(kullanicilar);
Next lesson: util.inspect