JavaScript and TypeScript course ยท Module 1: JavaScript Basics

First Steps - The JavaScript Console

6 min read ยท
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:

  1. 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
  2. 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:

node
> console.log("Welcome to the world of dinosaurs!");
Welcome 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:

// Simple mathematical operations
2 + 3     // 5
10 * 5    // 50
2 ** 8    // 256 (2 to the power of 8)

// String operations
"Tyranno" + "saurus" // "Tyrannosaurus"
"Veloci".toUpperCase() // "VELOCI"

// Logical operations
true && false // false
true || false // true
!true         // false

Using 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:

console.log("Welcome to Jurassic Park!");

const dinosaur = {
  species: "Velociraptor",
  height: 0.5, // meters
  speed: 40, // km/h
  dangerous: true
};

console.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:

// Warnings
console.warn("Warning! The Velociraptor fence has been damaged!");

// Errors
console.error("CRITICAL ERROR: Park security system disabled!");

// Information
console.info("New T-Rex hatching scheduled for 3:30 PM");

// Grouping logs
console.group("Dinosaur Status");
console.log("T-Rex: In enclosure");
console.log("Velociraptors: !!! NO DATA !!!");
console.log("Triceratops: In paddock");
console.groupEnd();

// Measuring execution time
console.time("DNA Sequencing");
// ... code whose execution time we want to measure
console.timeEnd("DNA Sequencing");

// Tables
console.table([
  { species: "T-Rex", status: "In enclosure", dangerous: true },
  { species: "Triceratops", status: "In paddock", dangerous: false },
  { species: "Velociraptor", status: "ESCAPED!", dangerous: true }
]);

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:

const dino = { species: "Velociraptor", paddock: 7 };
console.assert(dino.paddock === 7, "Dinosaur in wrong paddock!");  // Nothing is displayed
console.assert(dino.species === "T-Rex", "Incorrect species!");  // Displays error with message

Multi-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:

// Press Shift+Enter after each line except the last
function analyzeDNA(species) {
  console.log("Analyzing DNA for species: " + species);
  return `DNA of ${species} contains frog genetic sequences`;
}

analyzeDNA("Dilophosaurus"); // Press Enter to execute the function

Auto-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

  1. $0 - reference to the currently selected element in the Elements tab
  2. $ - 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)
  3. $_ - contains the value of the last executed expression
Math.random()  // e.g., 0.7589453290389485
$_             // returns the same result: 0.7589453290389485

Clearing the Console

When your "laboratory" becomes too cluttered, you can clear the console in several ways:

  1. Press Ctrl+L (Windows/Linux/Mac)
  2. Type console.clear()
  3. 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:

  1. JSFiddle, CodePen, CodeSandbox - online platforms allowing you to write and test JavaScript code along with HTML and CSS
  2. RunJS - a desktop application functioning as a JavaScript notebook with instant evaluation
  3. 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:

  1. Create an object representing a dinosaur with various properties

    const trex = {
      name: "Tyrannosaurus Rex",
      height: 5.6,
      weight: 8000,
      speed: 27,
      carnivoreDiet: true
    };
  2. Try different methods of displaying information about the dinosaur

    console.log(trex);
    console.table(trex);
    console.log(`${trex.name} weighs ${trex.weight} kg and runs at ${trex.speed} km/h`);
  3. Create an array of dinosaurs and filter it to find all carnivorous dinosaurs

    const dinosaurs = [
      { name: "T-Rex", carnivoreDiet: true, weight: 8000 },
      { name: "Velociraptor", carnivoreDiet: true, weight: 15 },
      { name: "Triceratops", carnivoreDiet: false, weight: 9000 },
      { name: "Brachiosaurus", carnivoreDiet: false, weight: 50000 }
    ];
    
    const carnivores = dinosaurs.filter(dino => dino.carnivoreDiet);
    console.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
// DNA Laboratory - Data Type Cataloging
// Exercise: Working with different data types

// String - text
const dinoName = "Tyrannosaurus Rex";
console.log("Species (string):", dinoName, typeof dinoName);

// Number
const dinoAge = 68000000;
console.log("Age (number):", dinoAge, typeof dinoAge);

// Boolean - logical value
const isDangerous = true;
console.log("Dangerous (boolean):", isDangerous, typeof isDangerous);

// null and undefined
const unknownDNA = null;
let pendingSample;
console.log("Unknown DNA (null):", unknownDNA, typeof unknownDNA);
console.log("Pending sample (undefined):", pendingSample, typeof pendingSample);

// Your task:
// 1. Create variables of different types for a dinosaur profile
// 2. Use typeof to check types
// 3. Display all data in the console

// Your code here:

Docs entries used in this lesson

Spotted 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:

  1. Coding taskPractice: console.log()
  2. Put in orderconsole.log Syntax
  3. Click in orderSorting: console.log with Concatenation

Useful articles