Lesson 1
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.
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:
<!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>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:
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".
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.
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:
<!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.
<!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>console.log("Hello from an external file!");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>.
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:
Ctrl + Shift + J(Windows/Linux) or Cmd + Option + J (Mac) in Chrome.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 orangeThe 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:
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"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.// 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.
Like a human language, JavaScript has a grammar that must be respected. Here are the basic rules to know right now:
;."..." or single quotes '...'.// 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 tooGet 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.
No installation is needed to get started: your browser is enough. Here are several ways to practice depending on your level and preferences:
.html and .js files.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.
myVariable andmyvariable are two different things).<script> before the HTML content without the defer attribute: the script might then look for elements that do not exist yet.consol.log instead of console.log.src attribute: the browser cannot find the script and nothing happens.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:
consol.log("Hello");
// Error in the console:
// Uncaught ReferenceError: consol is not defined
// → "consol" does not exist: the "e" in "console" is missingExercise 1: your first script
Create an index.html file with a<script> tag, then use console.log() to display in turn:
"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().
<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.