JavaScript and TypeScript course ยท Module 5: Advanced JavaScript
Browser Console and Its Functions
In this lesson6
Managing Jurassic Park is no easy task. When problems arise in the dinosaur tracking system or we need to quickly diagnose why the lockdown protocol isn't starting correctly, debugging is a critical skill. One of the most important diagnostic tools in JavaScript is the browser console.
In this exercise we'll learn about a tool that will be your best friend when searching for and solving problems - the browser developer console.
Opening the Developer Console
Before we start using the console, we need to know how to open it:
- Chrome/Edge: <kbd>F12</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>J</kbd> (Windows/Linux) or <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>J</kbd> (Mac)
- Firefox: <kbd>F12</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd> (Windows/Linux) or <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>K</kbd> (Mac)
- Safari: <kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>C</kbd> (you must first enable developer tools in settings)
After opening you'll see several tabs, including "Console". That's where we'll focus.
Basic Console Functions
1. console.log() - Your Best Friend
The most commonly used console function is console.log(). It displays values in the console, which is indispensable during debugging:
// Displaying simple values
console.log("Dinosaur tracking system started");
console.log(42); // number
console.log(true); // boolean value
// Displaying multiple values at once
const dinosaur = { name: "Rex", type: "T-Rex", status: "contained" };
console.log("Dinosaur data:", dinosaur, "Update:", new Date());
// String interpolation
const sector = "B7";
const threat = "high";
console.log(`Dinosaur detected in sector ${sector}. Threat level: ${threat}`);In our Jurassic Park system we can use console.log() to track various events:
function trackDinosaur(id, location) {
console.log(`Tracking dinosaur #${id} at location ${location}`);
// Tracking logic...
const status = checkContainment(id);
if (status !== "contained") {
console.log(`ALERT: Dinosaur #${id} is not in its enclosure! Current status: ${status}`);
}
return status;
}2. console.error(), console.warn(), console.info()
In addition to the standard log, we have special methods for different message levels:
// Errors - usually displayed in red
console.error("CRITICAL ERROR: Fence system failure in T-Rex sector!");
// Warnings - usually displayed in yellow
console.warn("Warning: Motion sensor battery level dropping below 20%");
// Info - often distinguished from regular logs
console.info("Info: Technical system review scheduled for tomorrow, 8:00");Using them helps visually distinguish message types in the console, which is especially important when dealing with large volumes of logs.
3. console.table() - Clean Display of Tabular Data
When dealing with arrays of objects, console.table() is invaluable:
// Array of dinosaurs in our park
const dinosaurs = [
{ id: 1, name: "Rex", species: "T-Rex", danger: 9, location: "Enclosure A" },
{ id: 2, name: "Blue", species: "Velociraptor", danger: 8, location: "Enclosure B" },
{ id: 3, name: "Delta", species: "Velociraptor", danger: 8, location: "Enclosure B" },
{ id: 4, name: "Echo", species: "Velociraptor", danger: 7, location: "Enclosure B" },
{ id: 5, name: "Trike", species: "Triceratops", danger: 4, location: "Enclosure C" }
];
// Displays a beautiful table with the data
console.table(dinosaurs);
// We can also select specific columns
console.table(dinosaurs, ["name", "species", "danger"]);This is especially useful for data analysis, checking API query results, or reviewing configurations.
4. console.group() - Grouping Logs
When we have many related logs, we can group them for clarity:
// Monitoring a specific dinosaur
function monitorDinosaur(dinosaur) {
console.group(`Monitoring: ${dinosaur.name} (${dinosaur.species})`);
console.log(`Location: ${dinosaur.location}`);
console.log(`Danger level: ${dinosaur.danger}/10`);
const healthStatus = checkHealth(dinosaur.id);
console.log(`Health status: ${healthStatus.status}`);
if (healthStatus.issues.length > 0) {
console.warn(`Health issues detected: ${healthStatus.issues.join(', ')}`);
}
const securityStatus = checkSecurity(dinosaur.location);
console.log(`Security status: ${securityStatus.status}`);
if (securityStatus.issues.length > 0) {
console.error(`Security issues: ${securityStatus.issues.join(', ')}`);
}
console.groupEnd();
return { healthStatus, securityStatus };
}
// Grouping can also be nested
function monitorAllDinosaurs(dinosaurs) {
console.group('Monitoring all dinosaurs');
dinosaurs.forEach(dino => {
monitorDinosaur(dino);
});
console.groupEnd();
}
monitorAllDinosaurs(dinosaurs);You can also start a group collapsed using console.groupCollapsed(), which is useful with many groups.
5. console.time() and console.timeEnd() - Measuring Execution Time
Sometimes we need to know how long certain operations take:
// Measuring module load time
console.time('Loading tracking module');
loadTrackingModule()
.then(() => {
console.timeEnd('Loading tracking module');
// Displays e.g.: "Loading tracking module: 235.41ms"
});
// We can have multiple parallel timers
console.time('System initialization');
console.time('Data processing');
initSystem()
.then(() => {
console.timeEnd('System initialization');
return processData();
})
.then(() => {
console.timeEnd('Data processing');
});This is extremely useful for identifying bottlenecks in applications and optimizing performance.
6. console.trace() - Call Stack Tracing
When you don't know exactly where a function was called from:
function monitorFenceStatus(sectorId) {
console.trace(`Checking fence status in sector ${sectorId}`);
// Rest of code...
}
function checkAllFences() {
const sectors = ['A1', 'B2', 'C3'];
sectors.forEach(monitorFenceStatus);
}
function dailySecurityCheck() {
checkAllFences();
}
dailySecurityCheck();console.trace() will display the full call stack, showing the exact execution path, which is invaluable when debugging complex calls.
7. console.assert() - Conditional Debug Messages
Checks a condition and displays an error when the condition is false:
function feedDinosaur(dinosaur, foodAmount) {
// Make sure the food amount is sufficient for the species
console.assert(
foodAmount >= getMinimumFoodRequirement(dinosaur.species),
`Insufficient food for ${dinosaur.name}! ` +
`Required minimum: ${getMinimumFoodRequirement(dinosaur.species)}kg, ` +
`Provided: ${foodAmount}kg`
);
// Rest of code...
}
feedDinosaur(dinosaurs[0], 5); // If 5kg is too little, we'll see an errorThis is useful for early detection of potential problems without stopping program execution.
8. console.count() - Counting Calls
Counting how many times a function or code block has been called:
function checkFenceVoltage(sectorId) {
console.count(`Voltage check in sector ${sectorId}`);
// Rest of code...
}
// Simulate regular checks
setInterval(() => checkFenceVoltage('A1'), 5000);
setInterval(() => checkFenceVoltage('B2'), 8000);After each call we'll see in the console something like:
Voltage check in sector A1: 1
Voltage check in sector A1: 2
Voltage check in sector B2: 1
Voltage check in sector A1: 3We can reset the counter using console.countReset('name').
9. console.dir() - Displaying Object Properties
When we want to see the full structure of an object:
const parkSystem = {
name: "Jurassic Park",
sectors: {
A: { dinosaurs: [/*...*/], status: "secure" },
B: { dinosaurs: [/*...*/], status: "alert" }
},
security: {
fences: { status: "online", voltage: 10000 },
cameras: { operational: 45, offline: 3 }
}
};
// Displays an interactive, expandable object structure
console.dir(parkSystem);This function is especially useful for complex objects, as it allows browsing nested properties.
10. Console Message Formatting
The console also supports basic formatting with format specifiers:
// Styling text with CSS
console.log(
"%cWARNING! %cCritical danger level %cin sector B!",
"color: red; font-size: 20px; font-weight: bold;",
"color: orange; font-size: 16px;",
"color: black; font-weight: bold;"
);
// Displaying variables in a message
console.log("Dinosaur %s has danger level %d", "Rex", 9);Advanced Console Features
1. Filtering Messages
Most browser consoles allow filtering displayed messages. We can filter by:
- Level (Error, Warning, Info, Log)
- Text (typing a search phrase)
- Source (e.g. only from a specific file)
This is extremely useful when dealing with large volumes of logs.
2. Saving to File
Console messages can usually be saved to a file, which is useful for log analysis:
- Right-click in the console
- Select "Save as..."
3. Clearing the Console
The console can be cleared in several ways:
- Clicking the crossed-circle icon in the console
- Pressing <kbd>Ctrl</kbd>+<kbd>L</kbd> (when the console is active)
- Using code:
console.clear()
4. Console as a REPL Environment
The browser console also works as a REPL (Read-Eval-Print Loop), meaning we can execute JavaScript code directly in it:
// Directly in console
const dinos = [{name: "Rex"}, {name: "Blue"}];
dinos.filter(d => d.name === "Blue");
// Defining functions
function alertSecurity(message) {
return `[SECURITY ALERT] ${message} - ${new Date().toISOString()}`;
}
// Using the function
alertSecurity("Fence breach in sector C2");This is extremely useful for testing small code snippets or debugging without modifying source code.
Practical Implementation in Our Jurassic Park System
Let's create a practical implementation of a logging system for our Jurassic Park that makes use of various console functions:
// Logger for the Jurassic Park system
class JurassicLogger {
constructor(moduleName) {
this.moduleName = moduleName;
this.logCount = 0;
this.errorCount = 0;
this.warnCount = 0;
}
log(...args) {
this.logCount++;
console.log(`[${this.moduleName}] `, ...args);
}
error(...args) {
this.errorCount++;
console.error(`[${this.moduleName}] ERROR:`, ...args);
}
warn(...args) {
this.warnCount++;
console.warn(`[${this.moduleName}] WARNING:`, ...args);
}
info(...args) {
console.info(`[${this.moduleName}] INFO:`, ...args);
}
startGroup(label) {
console.group(`[${this.moduleName}] ${label}`);
}
endGroup() {
console.groupEnd();
}
startTimer(label) {
console.time(`[${this.moduleName}] ${label}`);
}
endTimer(label) {
console.timeEnd(`[${this.moduleName}] ${label}`);
}
table(data, columns) {
console.log(`[${this.moduleName}] Tabular data:`);
console.table(data, columns);
}
getStats() {
return {
moduleName: this.moduleName,
logs: this.logCount,
errors: this.errorCount,
warnings: this.warnCount
};
}
trace(message) {
console.log(`[${this.moduleName}] TRACE: ${message}`);
console.trace();
}
assert(condition, message) {
console.assert(condition, `[${this.moduleName}] Assertion failed: ${message}`);
}
// Special formatting for security alerts
securityAlert(message, level = 'warning') {
const styles = {
warning: "background: #FFA500; color: black; padding: 2px 5px; border-radius: 3px;",
critical: "background: #FF0000; color: white; padding: 2px 5px; border-radius: 3px; font-weight: bold;",
info: "background: #0066FF; color: white; padding: 2px 5px; border-radius: 3px;"
};
console.log(
`%c[${this.moduleName}] SECURITY ALERT %c${message}`,
styles[level] || styles.warning,
"color: black;"
);
}
}
// Example usage
const securityLogger = new JurassicLogger('ParkSecurity');
const dinosaurLogger = new JurassicLogger('DinosaurTracker');
const systemLogger = new JurassicLogger('MainSystem');
// System initialization
systemLogger.startTimer('System initialization');
systemLogger.log('Starting Jurassic Park system initialization...');
setTimeout(() => {
systemLogger.info('Subsystems started');
systemLogger.endTimer('System initialization');
// Dinosaur information
const dinoData = [
{ id: 'TRX-01', name: 'Rex', species: 'T-Rex', status: 'contained', healthLevel: 92 },
{ id: 'VEL-01', name: 'Blue', species: 'Velociraptor', status: 'contained', healthLevel: 87 },
{ id: 'VEL-02', name: 'Delta', species: 'Velociraptor', status: 'sedated', healthLevel: 65 },
{ id: 'TRI-01', name: 'Sarah', species: 'Triceratops', status: 'contained', healthLevel: 95 }
];
dinosaurLogger.startGroup('Dinosaur status report');
dinosaurLogger.table(dinoData);
// Check dinosaur health
dinoData.forEach(dino => {
dinosaurLogger.startGroup(`Dinosaur: ${dino.name}`);
if (dino.healthLevel < 70) {
dinosaurLogger.warn(`Dinosaur ${dino.name} health level is low: ${dino.healthLevel}%`);
} else {
dinosaurLogger.log(`Health status: ${dino.healthLevel}%`);
}
if (dino.status !== 'contained') {
dinosaurLogger.error(`Dinosaur ${dino.name} is not in its enclosure! Status: ${dino.status}`);
securityLogger.securityAlert(`Dinosaur ${dino.name} (${dino.species}) status: ${dino.status}`, 'critical');
}
dinosaurLogger.endGroup();
});
dinosaurLogger.endGroup();
// Check security systems
securityLogger.startGroup('Security systems');
const fenceStatus = { sector: 'B', voltage: 9800, status: 'active' };
securityLogger.log(`Fence status in sector ${fenceStatus.sector}: ${fenceStatus.status}`);
securityLogger.assert(
fenceStatus.voltage >= 10000,
`Fence voltage in sector ${fenceStatus.sector} is too low: ${fenceStatus.voltage}V (min. 10000V)`
);
securityLogger.endGroup();
// Display log stats
systemLogger.startGroup('Log statistics');
console.table([
securityLogger.getStats(),
dinosaurLogger.getStats(),
systemLogger.getStats()
]);
systemLogger.endGroup();
}, 2000);Production and Development Logging
In real applications it's worth separating development logging from production logging:
// logger.js
class Logger {
constructor(isProduction = process.env.NODE_ENV === 'production') {
this.isProduction = isProduction;
}
log(...args) {
if (!this.isProduction) {
console.log(...args);
}
}
// For critical errors, we log even in production
error(...args) {
console.error(...args);
if (this.isProduction) {
// In production we can send errors to a monitoring service
this.sendToErrorMonitoring(args);
}
}
sendToErrorMonitoring(errorData) {
// Implementation for sending to Sentry, LogRocket, etc.
}
}
export default new Logger();Summary
The browser console is a powerful tool that greatly simplifies debugging and monitoring JavaScript applications. In the context of our Jurassic Park, good logging practices can be the difference between a smoothly running park and... well, the scenario from the movies!
Key functions to remember:
console.log()- basic loggingconsole.error(),console.warn(),console.info()- different message levelsconsole.table()- clean data displayconsole.group()- organizing related logsconsole.time()andconsole.timeEnd()- measuring performanceconsole.trace()- diagnosing where a call comes fromconsole.assert()- conditional debug messages
Remember to regularly use the console during development - it will help you detect and fix bugs faster, before the dinosaurs find a hole in your code!
Code for this lesson: main.js
// Re-exporting and module aggregation - Jurassic Park
// Creating "index" modules for easier importing
console.log("Re-exporting and Module Aggregation");
console.log("Module structure organization\n");
// ===========================================
// BASE MODULES
// ===========================================
// === types/DinosaurTypes.js ===
const DinosaurTypes = {
CARNIVORE: 'carnivore',
HERBIVORE: 'herbivore',
OMNIVORE: 'omnivore'
};
const DangerLevels = {
LOW: 1,
MEDIUM: 5,
HIGH: 7,
CRITICAL: 9
};
// === models/Dinosaur.js ===
class Dinosaur {
constructor(name, species, type, dangerLevel) {
this.name = name;
this.species = species;
this.type = type;
this.dangerLevel = dangerLevel;
this.health = 100;
this.id = Math.random().toString(36).substr(2, 9);
}
getInfo() {
return `${this.name} (${this.species}) - Danger: ${this.dangerLevel}/10`;
}
}
// === models/Enclosure.js ===
class Enclosure {
constructor(id, name, capacity) {
this.id = id;
this.name = name;
this.capacity = capacity;
this.dinosaurs = [];
}
addDinosaur(dinosaur) {
if (this.dinosaurs.length >= this.capacity) {
throw new Error('Enclosure is full');
}
this.dinosaurs.push(dinosaur);
}
getStatus() {
return `${this.name}: ${this.dinosaurs.length}/${this.capacity} dinosaurs`;
}
}
// === models/Visitor.js ===
class Visitor {
constructor(name, age, ticketType) {
this.name = name;
this.age = age;
this.ticketType = ticketType;
this.id = Math.random().toString(36).substr(2, 9);
}
getDetails() {
return `${this.name}, ${this.age} years old (${this.ticketType} ticket)`;
}
}
// === utils/validators.js ===
function validateDinosaur(data) {
const { name, species, type, dangerLevel } = data;
const errors = [];
if (!name || typeof name !== 'string') errors.push('Invalid name');
if (!species || typeof species !== 'string') errors.push('Invalid species');
if (!Object.values(DinosaurTypes).includes(type)) errors.push('Invalid type');
if (dangerLevel < 1 || dangerLevel > 10) errors.push('Danger level must be 1-10');
return { valid: errors.length === 0, errors };
}
function validateEnclosure(data) {
const { id, name, capacity } = data;
const errors = [];
if (!id || typeof id !== 'string') errors.push('Invalid id');
if (!name || typeof name !== 'string') errors.push('Invalid name');
if (!capacity || capacity < 1) errors.push('Capacity must be at least 1');
return { valid: errors.length === 0, errors };
}
// === utils/formatters.js ===
function formatDinosaurReport(dinosaur) {
return {
id: dinosaur.id,
name: dinosaur.name,
species: dinosaur.species,
type: dinosaur.type,
dangerLevel: dinosaur.dangerLevel,
health: `${dinosaur.health}%`,
status: dinosaur.health > 70 ? 'Good' : 'Needs attention'
};
}
function formatEnclosureReport(enclosure) {
return {
id: enclosure.id,
name: enclosure.name,
occupancy: `${enclosure.dinosaurs.length}/${enclosure.capacity}`,
dinosaurs: enclosure.dinosaurs.map(d => d.name),
status: enclosure.dinosaurs.length >= enclosure.capacity ? 'Full' : 'Available'
};
}
// ===========================================
// AGGREGATING MODULES (BARREL EXPORTS)
// ===========================================
// === models/index.js - Aggregating all models ===
// Re-exporting all models from one place
const ModelsModule = {
Dinosaur,
Enclosure,
Visitor
};
console.log("Models Module:");
console.log(" - Dinosaur");
console.log(" - Enclosure");
console.log(" - Visitor\n");
// === types/index.js - Type aggregation ===
const TypesModule = {
DinosaurTypes,
DangerLevels
};
console.log("Types Module:");
console.log(" - DinosaurTypes");
console.log(" - DangerLevels\n");
// === utils/index.js - Aggregating utilities ===
const UtilsModule = {
// validators
validateDinosaur,
validateEnclosure,
// formatters
formatDinosaurReport,
formatEnclosureReport
};
console.log("Utils Module:");
console.log(" - validateDinosaur");
console.log(" - validateEnclosure");
console.log(" - formatDinosaurReport");
console.log(" - formatEnclosureReport\n");
// === index.js - MAIN AGGREGATING MODULE ===
// Re-export everything from submodules
const JurassicParkSDK = {
// Models
...ModelsModule,
// Types
...TypesModule,
// Utils
...UtilsModule
};
console.log("Main SDK Module (All exports):");
console.log(" All models");
console.log(" All types");
console.log(" All utilities\n");
// ===========================================
// USAGE DEMONSTRATION
// ===========================================
console.log("=== RE-EXPORTING DEMO ===\n");
// Instead of importing from many places:
console.log("WITHOUT re-exports (many imports):");
console.log("import { Dinosaur } from './models/Dinosaur.js';");
console.log("import { Enclosure } from './models/Enclosure.js';");
console.log("import { DinosaurTypes } from './types/DinosaurTypes.js';");
console.log("import { validateDinosaur } from './utils/validators.js';");
console.log("import { formatDinosaurReport } from './utils/formatters.js';\n");
// We can import everything from one place:
console.log("WITH re-exports (one import):");
console.log("import {");
console.log(" Dinosaur, Enclosure,");
console.log(" DinosaurTypes,");
console.log(" validateDinosaur, formatDinosaurReport");
console.log("} from './index.js';\n");
console.log("=== PRACTICAL USAGE ===\n");
// Creating a dinosaur
const dinoData = {
name: 'Rexy',
species: 'Tyrannosaurus Rex',
type: JurassicParkSDK.DinosaurTypes.CARNIVORE,
dangerLevel: JurassicParkSDK.DangerLevels.CRITICAL
};
console.log("1. Validating the dinosaur data:");
const validation = JurassicParkSDK.validateDinosaur(dinoData);
console.log(` Valid: ${validation.valid}`);
if (validation.valid) {
const trex = new JurassicParkSDK.Dinosaur(
dinoData.name,
dinoData.species,
dinoData.type,
dinoData.dangerLevel
);
console.log(`\n2. Dinosaur created: ${trex.getInfo()}`);
const report = JurassicParkSDK.formatDinosaurReport(trex);
console.log("\n3. Dinosaur report:");
console.log(JSON.stringify(report, null, 2));
}
// Creating paddock
console.log("\n4. Creating paddock:");
const enclosureData = {
id: 'ENC-001',
name: 'T-Rex Paddock',
capacity: 2
};
const encValidation = JurassicParkSDK.validateEnclosure(enclosureData);
console.log(` Valid: ${encValidation.valid}`);
if (encValidation.valid) {
const paddock = new JurassicParkSDK.Enclosure(
enclosureData.id,
enclosureData.name,
enclosureData.capacity
);
const trex = new JurassicParkSDK.Dinosaur(
'Rexy',
'T-Rex',
JurassicParkSDK.DinosaurTypes.CARNIVORE,
9
);
paddock.addDinosaur(trex);
const encReport = JurassicParkSDK.formatEnclosureReport(paddock);
console.log("\n5. Paddock report:");
console.log(JSON.stringify(encReport, null, 2));
}
console.log("\n=== BENEFITS OF RE-EXPORTING ===\n");
console.log("Simpler imports:");
console.log(" - One import instead of many");
console.log(" - Cleaner code\n");
console.log("Better DX (Developer Experience):");
console.log(" - Easier API discovery");
console.log(" - Intuitive structure\n");
console.log("Easier refactoring:");
console.log(" - Changes to the internal structure don't affect users");
console.log(" - The public API stays stable\n");
console.log("Tree Shaking:");
console.log(" - Bundlers can remove unused code");
console.log(" - Smaller bundle size\n");
console.log("=== EXAMPLE PATTERNS ===\n");
console.log("// Basic re-export");
console.log("export { Dinosaur } from './Dinosaur.js';\n");
console.log("// Re-export with an alias");
console.log("export { Dinosaur as Dino } from './Dinosaur.js';\n");
console.log("// Re-export everything");
console.log("export * from './models.js';\n");
console.log("// Re-export with aggregation");
console.log("export { Dinosaur } from './Dinosaur.js';");
console.log("export { Enclosure } from './Enclosure.js';");
console.log("export { Visitor } from './Visitor.js';\n");
console.log("// Mixed export (default + named)");
console.log("export { default as Dinosaur, DinosaurTypes } from './Dinosaur.js';\n");
console.log("Demo completed!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which browser tool allows you to measure the execution time of a JavaScript code snippet?