Introduction to JavaScript
What JavaScript is, how it runs in the browser, and how to write your first lines of code.
1. Introduction
You have learned HTML (structure) and CSS (presentation). Now it is time for the third pillar of the web: JavaScript (behaviour).
JavaScript is the programming language that makes web pages interactive. It is what makes a button do something when you click it, validates a form before it is submitted, loads new content without refreshing the page, or animates an element in response to user action.
Unlike HTML and CSS, JavaScript is a full programming language with variables, logic, loops, and functions. You can think of it like this:
- HTML — the skeleton (structure and content)
- CSS — the skin and clothes (appearance)
- JavaScript — the muscles and brain (behaviour)
By the end of this lesson you will understand what JavaScript is, how to add it to an HTML page, and how to write and run your first simple statements.
2. Theory
2.1 What is JavaScript?
JavaScript (often abbreviated JS) is a high-level, interpreted programming language created in 1995 by Brendan Eich. It was originally designed to run inside web browsers, but today it also runs on servers (Node.js), mobile apps, desktop apps, and even databases.
Key characteristics:
- Interpreted — runs directly in the browser, no compilation step needed.
- Dynamic — variables can hold any type of value; types can change at runtime.
- Event-driven — most code runs in response to user actions (clicks, keypresses, etc.).
- Single-threaded — one operation runs at a time, but asynchronous patterns allow non-blocking behaviour.
2.2 How JavaScript runs in the browser
Every modern browser has a JavaScript engine built in:
- Chrome / Edge — V8
- Firefox — SpiderMonkey
- Safari — JavaScriptCore (Nitro)
When the browser loads an HTML page, the engine reads and executes any JavaScript it finds, top to bottom. The JS can then read and modify the page's HTML and CSS through the DOM (Document Object Model) — which you will learn in Module 10.
2.3 Three ways to add JavaScript to a page
1. Inline (inside an HTML attribute)
<button onclick="alert('Hello!')">Click me</button>
Avoid this — mixing HTML and JavaScript makes code hard to read and maintain.
2. Internal (inside a <script> tag)
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<h1>My Page</h1>
<script>
console.log('Hello from internal script!');
</script>
</body>
</html>
Good for small demos and learning. For real projects, use external files.
3. External (separate .js file)
<!-- HTML file -->
<body>
<h1>My Page</h1>
<script src="app.js"></script>
</body>
// app.js
console.log('Hello from external script!');
This is the correct approach for real projects. Keeps HTML and JS separate, allows caching, and keeps files manageable.
2.4 Where to place the <script> tag
Place <script> tags at the bottom of <body>, just before </body>. This ensures the HTML is fully loaded before the script runs — otherwise your JS might try to access elements that do not exist yet.
<!-- Recommended position -->
<body>
<!-- All your HTML content -->
<script src="app.js"></script>
</body>
Alternatively, use the defer attribute in the <head>:
<head>
<script src="app.js" defer></script>
</head>
defer tells the browser to download the script while parsing HTML, then run it after the HTML is fully parsed.
2.5 The console — your best friend
The browser's Developer Tools console lets you run JavaScript instantly and see output from your code.
Open DevTools: press F12 (or Cmd+Option+I on Mac) → click the Console tab.
// Print a message
console.log('Hello, World!');
// Print multiple values
console.log('Name:', 'Alice', 'Age:', 25);
// Print an error (shown in red)
console.error('Something went wrong');
// Print a warning (shown in yellow)
console.warn('This is deprecated');
// Print a table
console.table([1, 2, 3]);
You can also type JavaScript directly into the console and press Enter to run it immediately. Try it now!
2.6 Statements and semicolons
A JavaScript program is a list of statements — instructions for the engine to execute. Each statement is typically one action.
console.log('First statement');
console.log('Second statement');
console.log('Third statement');
Semicolons (;) mark the end of a statement. In modern JavaScript they are technically optional (the engine can usually infer them), but including them is good practice to avoid rare edge-case bugs.
2.7 Comments
Comments are notes for humans — the engine ignores them.
// This is a single-line comment
/*
This is a
multi-line comment
*/
console.log('This runs'); // Inline comment after code
2.8 Your first program
// Greet the user
console.log('Welcome to JavaScript!');
// Simple arithmetic
console.log(2 + 2); // 4
console.log(10 * 5); // 50
console.log(100 / 4); // 25
// String concatenation
console.log('Hello' + ', ' + 'World!'); // Hello, World!
2.9 alert, confirm, prompt
Three built-in browser functions that display dialog boxes — useful for quick demos but not used in real applications:
// Show a message
alert('Hello!');
// Ask yes/no — returns true or false
const answer = confirm('Are you sure?');
console.log(answer); // true if OK, false if Cancel
// Ask for text input — returns the entered string
const name = prompt('What is your name?');
console.log('Hello, ' + name);
3. Real World Example
When you visit a website and click a "Like" button:
- An HTML
<button>element is on the page. - CSS styles it to look like a like button.
- JavaScript listens for the click event (Module 11), sends a request to a server (Module 14), then updates the like count displayed on the page (Module 10) — all without reloading the page.
At its simplest, the JavaScript for a counter looks like this:
let likes = 0;
function addLike() {
likes = likes + 1;
console.log('Likes:', likes);
}
// Every time the button is clicked, call addLike()
document.querySelector('#like-btn').addEventListener('click', addLike);
You will understand every part of this by the end of Module 09.
4. Code Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First JavaScript</title>
</head>
<body>
<h1>JavaScript Introduction</h1>
<p>Open the DevTools Console (F12) to see output.</p>
<button id="greet-btn">Say Hello</button>
<p id="message"></p>
<script>
// 1. Log to the console
console.log('Script loaded!');
console.log('2 + 2 =', 2 + 2);
console.log('10 * 3 =', 10 * 3);
// 2. A simple function
function greet(name) {
return 'Hello, ' + name + '!';
}
// 3. Connect a button to a function
const btn = document.querySelector('#greet-btn');
const msg = document.querySelector('#message');
btn.addEventListener('click', function () {
const name = prompt('What is your name?') || 'World';
msg.textContent = greet(name);
console.log('Button clicked! Greeted:', name);
});
</script>
</body>
</html>
5. Code Breakdown
Script placement (before </body>)
The <script> tag is at the bottom of <body>. By the time it runs, the <button> and <p> elements already exist in the page, so document.querySelector can find them.
console.log()
The first three statements print to the console. You can pass multiple comma-separated values and the engine will display them all. Strings appear as-is; expressions like 2 + 2 are evaluated first, then the result (4) is printed.
function greet(name)
This defines a reusable block of code. When called with a name argument (e.g., greet('Alice')), it returns the string 'Hello, Alice!'. You will learn functions in depth in Lesson 7.
document.querySelector()
This finds an HTML element on the page using a CSS selector string. '#greet-btn' finds the element with id greet-btn. You will learn DOM manipulation in detail in Module 10.
addEventListener('click', ...)
Tells the browser: "When this button is clicked, run this function." The function inside prompts for a name, calls greet(), and displays the result in the paragraph. You will learn events in Module 11.
|| 'World' (fallback)
prompt() returns null if the user clicks Cancel. The || operator means "use 'World' if the left side is falsy." So if the user cancels, the greeting defaults to "Hello, World!".
6. Common Mistakes
Mistake 1 — Script in <head> without defer
<!-- Bad — JS runs before HTML is loaded; querySelector returns null -->
<head>
<script src="app.js"></script>
</head>
<!-- Good option 1 — bottom of body -->
<body>
...
<script src="app.js"></script>
</body>
<!-- Good option 2 — defer in head -->
<head>
<script src="app.js" defer></script>
</head>
Mistake 2 — Using = instead of == or ===
// Bad — this assigns 5 to x instead of comparing
if (x = 5) { ... }
// Good — comparison
if (x === 5) { ... }
Mistake 3 — Case sensitivity
// Bad — console.Log does not exist (capital L)
Console.Log('hello');
console.Log('hello');
// Good
console.log('hello');
Mistake 4 — Missing quotes around strings
// Bad — JS tries to find a variable called hello
console.log(hello);
// Good
console.log('hello');
Mistake 5 — Calling a function before it is defined (with function expressions)
// Bad — greet is a const (not hoisted)
greet(); // ReferenceError
const greet = function() { ... };
// OK — function declarations are hoisted
greet(); // works
function greet() { ... }
7. Best Practices
- Use external .js files for all but the simplest demos — keeps code organised and cacheable.
- Place scripts at the bottom of <body> or use the
deferattribute. - Use console.log() liberally while learning — it is the fastest way to understand what your code is doing.
- Write one statement per line — easier to read and debug.
- Use consistent indentation (2 or 4 spaces) — code that is hard to read is hard to debug.
- Comment your code when the intent is not obvious — write why, not what.
- Use strict mode — add
'use strict';at the top of scripts to catch common bugs early. - Never use inline event handlers (
onclick="...") in production — useaddEventListenerinstead. - Open DevTools before you test your code — errors appear in the Console tab in red.
- Read error messages carefully — they tell you the file, line number, and type of error.
8. Practice Exercise
Create your first JavaScript file.
Requirements
- Create an HTML file with a
<script>tag at the bottom of<body>. - Log your name to the console:
console.log('My name is ...'); - Log the result of these calculations:
- 15 + 27
- 100 - 43
- 6 * 8
- 144 / 12
- 17 % 5 (remainder/modulo)
- Log the following string using concatenation:
'I am learning JavaScript in ' + currentYear(compute the year withnew Date().getFullYear()). - Add a button to the HTML. When clicked, it should show an
alertsaying "Button clicked!".
Bonus
- Move your JavaScript to a separate
app.jsfile and link it with<script src="app.js"></script>. - Add a
promptthat asks for the user's name and then logs'Hello, NAME!'to the console.
9. Assignment
Build a simple interactive greeting page.
- Create an HTML page with: a heading, a text input, a button, and a paragraph to display output.
- Link an external
app.jsfile using<script src="app.js" defer></script>in the<head>. - In
app.js, write a functiongreet(name)that returns the string'Hello, ' + name + '! Welcome to JavaScript.' - When the button is clicked, read the value from the text input, call
greet(), and display the result in the paragraph. - If the input is empty, display "Please enter your name." instead.
- Log every button click to the console with a timestamp:
console.log('Greeted at:', new Date().toLocaleTimeString()).
Deliverable: Two files — index.html and app.js. Open the browser console while testing to confirm your log messages appear.
10. Interview Questions
- What is JavaScript and what is it used for?
JavaScript is a high-level, interpreted programming language that runs in the browser. It is used to add interactivity and behaviour to web pages — responding to user input, updating content without page reloads, communicating with servers, and more. - What are the three ways to include JavaScript in an HTML page?
Inline (onclick attribute), internal (<script> tag in the HTML), and external (separate .js file linked with <script src>). External files are preferred in production. - Why should <script> tags be placed at the bottom of <body>?
So the HTML is fully parsed before the script runs. If the script is in the <head>, it may try to access HTML elements that haven't loaded yet, resulting in null reference errors. The defer attribute achieves the same result from the <head>. - What does console.log() do?
It prints values to the browser's Developer Tools console. It is the primary tool for debugging and observing what a script is doing during development. - What is the difference between = and ===?
= is the assignment operator (sets a variable's value). === is the strict equality operator (compares two values without type coercion). Using = in an if condition is a common bug. - What does the defer attribute on a <script> tag do?
It tells the browser to download the script while parsing HTML, then execute it after the full HTML document has been parsed. It is equivalent to placing the script at the bottom of body.
11. Additional Resources
- MDN — JavaScript Guide: Introduction — official, authoritative documentation
- javascript.info — Introduction — best free JS textbook online
- MDN — console API — all console methods (log, warn, error, table, time…)
- Chrome DevTools — Console overview — Google's guide to using the console
- Eloquent JavaScript (free online book) — deep dive into JS fundamentals