JavaScript and TypeScript course Β· Module 1: JavaScript Basics
First Steps - The JavaScript Console
In this lesson10
Welcome to the genetic laboratory of Jurassic Park! Just as the park's scientists needed specialized equipment to study dinosaur DNA, we also need a tool for experimenting with JavaScript code. That tool is the JavaScript console - our own laboratory for testing and experimenting with the language.
What is the JavaScript Console?
The JavaScript console is an interactive environment that allows you to execute JavaScript code in real-time and immediately observe results. It's like a geneticist's microscope - it lets you precisely observe how our code behaves.
How to Access the JavaScript Console?
In the Browser
Every modern browser has a built-in JavaScript console, accessible through developer tools. Here's how to access it:
Chrome, Edge, Firefox, Safari:
- Press F12 or Ctrl+Shift+I (Windows/Linux) / Cmd+Option+I (Mac)
- Alternatively, right-click on the page and select "Inspect" or "Developer Tools"
- Navigate to the "Console" tab
Direct console shortcut:
- Ctrl+Shift+J (Windows/Linux)
- Cmd+Option+J (Mac)
In Node.js
If you have Node.js installed, you can access the JavaScript console by simply typing node in the terminal:
1node
2> console.log("Welcome to the world of dinosaurs!");
3Welcome to the world of dinosaurs!Using the Console for Experiments
Basic Operations
The JavaScript console is the ideal place to experiment with simple expressions and operations. Just as the genetic laboratory in Jurassic Park allowed for DNA experiments, the console allows for testing language features:
1// Simple mathematical operations
22 + 3 // 5
310 * 5 // 50
42 ** 8 // 256 (2 to the power of 8)
5
6// String operations
7"Tyranno" + "saurus" // "Tyrannosaurus"
8"Veloci".toUpperCase() // "VELOCI"
9
10// Logical operations
11true && false // false
12true || false // true
13!true // falseUsing console.log()
The console.log() method is one of the most important tools when learning and debugging JavaScript - it's like a monitoring camera in Jurassic Park, allowing you to observe what's happening in our code:
1console.log("Welcome to Jurassic Park!");
2
3const dinosaur = {
4 species: "Velociraptor",
5 height: 0.5, // meters
6 speed: 40, // km/h
7 dangerous: true
8};
9
10console.log(dinosaur);Other Useful Console Object Methods
The console offers more than just log(). Just like different types of equipment in the laboratory, each method has its use:
1// Warnings
2console.warn("Warning! The Velociraptor fence has been damaged!");
3
4// Errors
5console.error("CRITICAL ERROR: Park security system disabled!");
6
7// Information
8console.info("New T-Rex hatching scheduled for 3:30 PM");
9
10// Grouping logs
11console.group("Dinosaur Status");
12console.log("T-Rex: In enclosure");
13console.log("Velociraptors: !!! NO DATA !!!");
14console.log("Triceratops: In paddock");
15console.groupEnd();
16
17// Measuring execution time
18console.time("DNA Sequencing");
19// ... code whose execution time we want to measure
20console.timeEnd("DNA Sequencing");
21
22// Tables
23console.table([
24 { species: "T-Rex", status: "In enclosure", dangerous: true },
25 { species: "Triceratops", status: "In paddock", dangerous: false },
26 { species: "Velociraptor", status: "ESCAPED!", dangerous: true }
27]);Debugging with console.assert()
The console.assert() method allows you to test conditions and displays a message only when the condition is false. It's like the security system in Jurassic Park that alerts only when something goes wrong:
1const dino = { species: "Velociraptor", paddock: 7 };
2console.assert(dino.paddock === 7, "Dinosaur in wrong paddock!"); // Nothing is displayed
3console.assert(dino.species === "T-Rex", "Incorrect species!"); // Displays error with messageMulti-line Commands in the Console
In the browser console, you can also write code on multiple lines. Use Shift+Enter to go to a new line without executing the code:
1// Press Shift+Enter after each line except the last
2function analyzeDNA(species) {
3 console.log("Analyzing DNA for species: " + species);
4 return `DNA of ${species} contains frog genetic sequences`;
5}
6
7analyzeDNA("Dilophosaurus"); // Press Enter to execute the functionAuto-completion and Command History
Most JavaScript consoles offer helpful features that speed up work:
- Auto-completion - after typing part of a variable or method name, press Tab for the console to automatically complete the name
- Command history - use the up and down arrows to browse previously entered commands
Useful Shortcuts and Tips
- $0 - reference to the currently selected element in the Elements tab
- $ - shortcut for document.querySelector(), e.g., $('div') returns the first div element on the page, and $$ - shortcut for document.querySelectorAll(), e.g., $$('div') returns all div elements (as an array)
- $_ - contains the value of the last executed expression
1Math.random() // e.g., 0.7589453290389485
2$_ // returns the same result: 0.7589453290389485Clearing the Console
When your "laboratory" becomes too cluttered, you can clear the console in several ways:
- Press Ctrl+L (Windows/Linux/Mac)
- Type
console.clear() - Click the trash icon in the browser console
Other Types of Consoles Useful for Learning JavaScript
Besides the browser console and Node.js, there are other environments that make it easier to experiment with JavaScript:
- JSFiddle, CodePen, CodeSandbox - online platforms allowing you to write and test JavaScript code along with HTML and CSS
- RunJS - a desktop application functioning as a JavaScript notebook with instant evaluation
- Quokka.js - an extension for code editors, enabling real-time result preview
Practical Exercise
Time for your own experiments! Open the JavaScript console in your browser and try the following examples:
Create an object representing a dinosaur with various properties
1const trex = { 2 name: "Tyrannosaurus Rex", 3 height: 5.6, 4 weight: 8000, 5 speed: 27, 6 carnivoreDiet: true 7};Try different methods of displaying information about the dinosaur
1console.log(trex); 2console.table(trex); 3console.log(`${trex.name} weighs ${trex.weight} kg and runs at ${trex.speed} km/h`);Create an array of dinosaurs and filter it to find all carnivorous dinosaurs
1const dinosaurs = [ 2 { name: "T-Rex", carnivoreDiet: true, weight: 8000 }, 3 { name: "Velociraptor", carnivoreDiet: true, weight: 15 }, 4 { name: "Triceratops", carnivoreDiet: false, weight: 9000 }, 5 { name: "Brachiosaurus", carnivoreDiet: false, weight: 50000 } 6]; 7 8const carnivores = dinosaurs.filter(dino => dino.carnivoreDiet); 9console.table(carnivores);
Summary
The JavaScript console is your personal laboratory for experimenting with code. Just as the scientists in Jurassic Park had to first test their theories in the laboratory before applying them to live dinosaurs, you should use the console to experiment with JavaScript before implementing code in real applications.
In the following lessons, we will frequently use the console to test new JavaScript concepts and features. The more you experiment, the better you understand how the language works - just like Dr. Henry Wu, the chief geneticist of Jurassic Park, who through continuous experiments became an expert on dinosaur DNA.
Remember: unlike experiments in Jurassic Park, experiments in the JavaScript console are completely safe - no T-Rex will escape from your browser!
Code for this lesson: index.js
1// DNA Laboratory - Data Type Cataloging
2// Exercise: Working with different data types
3
4// String - text
5const dinoName = "Tyrannosaurus Rex";
6console.log("Species (string):", dinoName, typeof dinoName);
7
8// Number
9const dinoAge = 68000000;
10console.log("Age (number):", dinoAge, typeof dinoAge);
11
12// Boolean - logical value
13const isDangerous = true;
14console.log("Dangerous (boolean):", isDangerous, typeof isDangerous);
15
16// null and undefined
17const unknownDNA = null;
18let pendingSample;
19console.log("Unknown DNA (null):", unknownDNA, typeof unknownDNA);
20console.log("Pending sample (undefined):", pendingSample, typeof pendingSample);
21
22// Your task:
23// 1. Create variables of different types for a dinosaur profile
24// 2. Use typeof to check types
25// 3. Display all data in the console
26
27// Your code here:
28Spotted a mistake in this lesson?
Hands-on tasks in the game
- Code editor
Write a program that displays: 'Lab status: ACTIVE', then 'Number of DNA samples: 15', and finally 'System readiness: 100%'. Use 3 separate console.log() calls.
- Horizontal ordering
Arrange the elements for printing text to the console:
- Click in order
Arrange the console.log elements with a variable: