Lesson 1 / 1010%

Lesson 1

Introduction

12 min

Understand what JavaScript is and how it applies to an HTML page.

Definition

JavaScript is an interpreted programming language, high-level and multi-paradigm, created to add interactivity andbehavior to web pages. It is run by an engine built into the browser (or by an environment such as Node.js) that reads the programmer's instructions and applies them in real time, without a prior compilation step.

What is JavaScript?

JavaScript (often shortened to JS) is a programming language that makes a web page interactive. It is one of the three pillars of web development, alongsideHTML (which structures the content) andCSS (which handles the appearance). Where HTML and CSS build a static set, JavaScript brings it to life: it can react to a click, validate a form before it is sent, show or hide elements, animate an interface, perform calculations in real time, or fetch data from a server without reloading the page.

In practice, without JavaScript a web page stays frozen: you can read it, but it reacts to nothing. With JavaScript, a website becomes a real application that can respond to its user's actions.

To understand the role of each language, you can compare a web page to a house. HTML is the framework: the walls, the rooms, the doors. CSS is the decoration: the colors, the furniture, the layout. JavaScript is the electricity: it is thanks to it that the light turns on when you press the switch, that the door opens when someone rings the bell, that the house reacts to what its occupants do.

Here is a minimal example that brings the three languages together. The HTML creates a button, the CSS colors it, and the JavaScript displays a message when it is clicked:

the-three-pillars.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>HTML + CSS + JavaScript</title>
    <style>
      /* CSS: the appearance */
      button {
        background-color: royalblue;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
      }
    </style>
  </head>
  <body>
    <!-- HTML: the structure -->
    <button id="myButton">Click me</button>

    <script>
      // JavaScript: the behavior
      const button = document.getElementById("myButton");
      button.addEventListener("click", function () {
        alert("Well done, you just ran your first script!");
      });
    </script>
  </body>
</html>

What can you do with JavaScript?

JavaScript is an extremely versatile language. When you browse the web, you come across it constantly without even realizing it. Here are some concrete examples of what it makes possible:

  • React to user actions: clicking a button, hovering over an image, pressing a key on the keyboard, scrolling the page.
  • Validate forms: check that an email address is valid or that a password is long enough before the data is even sent.
  • Modify the page dynamically: add, remove or change HTML elements and their style without reloading the page (dropdown menus, modal windows, tabs, image carousels).
  • Communicate with a server: load new messages on a social network, update a shopping cart or display the weather in real time, without leaving the page.
  • Create animations and games: move elements, draw on a canvas, program a platform game or a simple guessing game.
  • Build complete applications: complex websites, mobile apps, desktop software and even programs that run on servers.

A bit of history and context

JavaScript was created in 1995 by Brendan Eich, in just ten days, for the Netscape Navigator browser. Since then it has kept evolving and has become, according to most annual developer surveys,the most widely used programming language in the world.

Despite the similarity of their names,JavaScript has nothing to do with Java. They are two distinct languages, designed for different purposes. The name "JavaScript" was actually a marketing choice at the time, as Java was very popular back then. A commonly used comparison: Java is to JavaScript what "car" is to "carpet".

  • JavaScript is standardized under the name ECMAScript (often abbreviated ES). Modern versions (ES6 and later) bring a clearer and more powerful syntax.
  • It runs natively in every browser (Chrome, Firefox, Safari, Edge...), with no installation or prior compilation.
  • Thanks to Node.js, JavaScript can also run on the server side, which makes it possible to write a complete website (frontend and backend) in a single language.
  • Frameworks such as React, Vue orAngular are built on JavaScript and make it possible to create complex, high-performance web applications.

Where does JavaScript run? Client side and server side

When you visit a website, two actors come into play: theclient (your browser, on your computer or phone) and theserver (a remote computer that stores the site and its data). JavaScript can run on both sides.

  • Client side: the code is downloaded with the page and then executed by the browser. This is JavaScript's historical use case, and the one we will study in this course. It is used to manage the interface and interactions.
  • Server side: thanks to Node.js, the code runs on the server to manage databases, user authentication or the business logic of a site.

Adding JavaScript to an HTML page

There are several ways to add JavaScript to a web page. The simplest is to use the <script> tag directly in the HTML. This is called an internal (or "inline") script:

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>My first JavaScript page</title>
  </head>
  <body>
    <h1>Hello!</h1>

    <script>
      console.log("Hello from JavaScript!");
    </script>
  </body>
</html>

In most real-world projects, however, it is preferable to write the JavaScript in a separate file (for examplescript.js) and link it to the HTML page with thesrc attribute. This keeps the code organized and lets you reuse it across several pages. This is called anexternal script.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>My page</title>
  </head>
  <body>
    <h1>Hello!</h1>

    <!-- "defer" ensures the script runs
         after the HTML has been fully loaded -->
    <script src="script.js" defer></script>
  </body>
</html>
script.js
console.log("Hello from an external file!");

Why the defer attribute?

The browser reads an HTML page from top to bottom. If your script is loaded before the rest of the page exists, it cannot manipulate elements that are not there yet. The defer attribute tells the browser to download the script in parallel, but to run it onlyonce the page has been fully parsed. Another classic solution is to place the <script> tag at the very end of the <body>.

The browser console: your best beginner's tool

console.log(...) is the most commonly used statement when learning to code. It displays a value or a message in thebrowser console, a built-in tool that lets you see what your code is doing, display variable values, and spot any errors.

To open it:

  • Right-click on the page, then choose "Inspect" (or "Inspect Element").
  • Click on the "Console" tab in the panel that opens.
  • Or use the keyboard shortcut Ctrl + Shift + J(Windows/Linux) or Cmd + Option + J (Mac) in Chrome.
console.js
console.log("A simple message");
console.log(42);
console.log(true);
console.log("Result:", 5 + 3);

console.error("This is an error"); // displayed in red
console.warn("This is a warning"); // displayed in orange

The console accepts several values separated by commas, which lets you display text and the result of a calculation on the same line. It can also present data as a table, which is very handy for inspecting several items at once:

advanced-console.js
console.log("First name:", "Aina", "| Age:", 17);

// Display data as a table
console.table([
  { firstName: "Aina", age: 17 },
  { firstName: "Hery", age: 19 },
]);

// Find out the type of a value
console.log(typeof "Hello"); // "string"
console.log(typeof 42);      // "number"

Your first interactive program

The console is useful for the developer, but JavaScript is mostly used to communicate with the user. For this, the browser offers three very simple little windows, ideal for getting started:

  • alert("message") displays a window containing a message and an "OK" button.
  • prompt("question") asks the user a question and retrieves their answer as text.
  • confirm("question") offers the choices "OK" and "Cancel" and returns true or false.
interaction.js
// We ask the user for their first name
const firstName = prompt("What's your name?");

// We reply with an alert window
alert("Hello " + firstName + "! Welcome to the world of JavaScript.");

// We also display the first name in the console
console.log("The visitor's name is", firstName);

In this example, firstName is a variable: a kind of named box that stores a value so it can be reused later. We will study variables in detail in the next lesson. For now, just remember that a JavaScript program is a series of instructions executed one after the other, from top to bottom.

The first syntax rules

Like a human language, JavaScript has a grammar that must be respected. Here are the basic rules to know right now:

  • A statement is a line of code that performs an action. It is generally ended with a semicolon ;.
  • Strings (text) are written between double quotes"..." or single quotes '...'.
  • Parentheses, braces and quotes must always be closed, otherwise the program causes an error.
  • Comments are notes for humans, ignored by the computer. They are used to explain your code.
syntax.js
// This is a single-line comment

/*
  This is a comment
  spanning several lines
*/

console.log("Hello"); // a statement ended with a semicolon
console.log('Hello'); // single quotes work too

Get into the habit of commenting your code right now, and ofindenting it (shifting lines with spaces) so that it stays readable. Clear code is much easier to reread, fix and share.

Where and how to practice JavaScript?

No installation is needed to get started: your browser is enough. Here are several ways to practice depending on your level and preferences:

  • Directly in the browser console, to quickly test a line of code.
  • In a code editor such as Visual Studio Code, by creating.html and .js files.
  • On online platforms such as CodePen, JSFiddle or Replit, which require no installation.

If you want to work seriously, we recommend installingVisual Studio Code, a free editor that colors your code, flags typos and offers autocompletion. With the "Live Server" extension, the page refreshes automatically every time you save a file, which makes learning much smoother. Here is a tutorial to install and configure it:Getting started with VSCode.

Common mistakes for beginners to avoid

  • Forgetting the semicolon at the end of a statement: it is not always mandatory, but it is a good habit to adopt.
  • Mixing up uppercase and lowercase: JavaScript iscase-sensitive (myVariable andmyvariable are two different things).
  • Placing your <script> before the HTML content without the defer attribute: the script might then look for elements that do not exist yet.
  • Forgetting to close a quote, a parenthesis or a brace: the program does not start and the console displays a syntax error.
  • Misspelling the name of a statement, for exampleconsol.log instead of console.log.
  • Getting the file path wrong in the src attribute: the browser cannot find the script and nothing happens.

Learning to read an error message

When your code contains a mistake, the console displays an error message in red, along with the file name and line number concerned. Don't panic: these messages are your allies, because they tell you exactly where to look. Take a look at the following example:

error.js
consol.log("Hello");
// Error in the console:
// Uncaught ReferenceError: consol is not defined
// → "consol" does not exist: the "e" in "console" is missing

Exercise 1: your first script

Create an index.html file with a<script> tag, then use console.log() to display in turn:

  1. Your first name
  2. Your age
  3. A sentence combining both, for example"My name is ... and I am ... years old"

Then open your browser's console to check that the three messages are displayed correctly.

Exercise 2: talking to the user

Write a script that uses prompt() to ask the user for their first name and their city, then uses alert() to display a personalized welcome sentence, for example"Hello Aina, welcome to Antananarivo!".

Bonus: also display the same sentence in the console withconsole.log().

Key takeaways

  • JavaScript is a programming language that makes a web page interactive and responsive to user actions.
  • HTML structures, CSS decorates, JavaScript animates: the three languages are complementary.
  • It runs directly in the browser, with no installation, and can also run on the server side with Node.js.
  • JavaScript has no connection with Java despite the similarity of their names.
  • It is added with the <script> tag, ideally in an external file loaded with the defer attribute.
  • console.log() is the essential tool for displaying values and debugging your code.
  • alert(), prompt() and confirm()let you talk to the user in a simple way.
  • JavaScript is case-sensitive, and an error message in the console is always a valuable clue for fixing your code.