Topic 1: Introduction to JavaScript
📖 14 min read · 🎯 beginner · 🧭 Prerequisites: css-introduction-internal-external-inline-task-form-internal
Why this matters
Up until now, everything you've built just sits there. HTML gives the page structure, CSS makes it look good — but if you click a button, nothing happens. If you fill in a form, nothing responds. That's fine for a flyer, but not for a real website. JavaScript is what changes that. It's the language that makes a page react to you — show a menu when you click, check if you typed a valid email, update content without reloading. This lesson is where your pages stop being static and start feeling alive.
What You'll Learn
- What JavaScript is and how it fits alongside HTML and CSS
- How to embed JavaScript inline and link it as an external file
- How to declare variables using
let,const, andvar - The core data types JavaScript supports: numbers, strings, booleans, arrays, and objects
- Every arithmetic, assignment, comparison, and logical operator
- How to control program flow with
if...else,switch,for, andwhile
The Analogy
Think of a building. HTML is the steel frame and concrete — it gives the building its rooms and floors. CSS is the interior design — paint colours, furniture placement, lighting fixtures. JavaScript is the electrical wiring and plumbing: invisible until you flip a switch or turn a tap, but the moment you do, something happens. Without JavaScript, clicking a button on a webpage is like flipping a light switch in a house with no wiring — the switch is there, it looks right, but nothing turns on. JavaScript closes that circuit between user action and browser response.
Chapter 1: What is JavaScript?
JavaScript is a versatile, high-level programming language that is essential for web development. It runs directly in the browser, enabling interactive features and dynamic content on web pages without requiring a page reload.
The three pillars of a modern web page map cleanly to three languages:
| Layer | Language | Job |
|---|---|---|
| Structure | HTML | Defines what is on the page |
| Presentation | CSS | Defines how it looks |
| Behaviour | JavaScript | Defines what it does |
JavaScript is the only one of the three that can react — to a click, a key press, a timer, or data arriving from a server. It executes inside the browser's JavaScript engine (V8 in Chrome, SpiderMonkey in Firefox), which means no installation is required for the user.
Key characteristics of JavaScript:
- Interpreted: code runs line-by-line; no separate compile step in the browser
- Dynamically typed: variables hold any type; types are checked at runtime
- Event-driven: code can be triggered by user actions, timers, or network events
- Cross-platform: runs in every modern browser on every major OS
Chapter 2: Adding JavaScript to a Web Page
There are two main ways to include JavaScript in an HTML document: inline (inside a <script> tag in the HTML file) and external (a separate .js file linked with a <script src=""> tag).
Inline JavaScript
The <script> tag can appear anywhere in the HTML, though placing it just before </body> is common so the page content loads first.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline JavaScript Example</title>
</head>
<body>
<h1>Welcome to Vizag</h1>
<button onclick="greet()">Click Me</button>
<script>
function greet() {
alert('Hello, Vizag!');
}
</script>
</body>
</html>
When the button is clicked, the browser calls greet(), which triggers alert() — a built-in function that opens a popup dialog.
External JavaScript
For larger projects, keeping JavaScript in a separate file keeps your HTML clean and allows the same script to be reused across multiple pages.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Welcome to Vizag</h1>
<button onclick="greet()">Click Me</button>
</body>
</html>
script.js:
function greet() {
alert('Hello, Vizag!');
}
The defer attribute on the <script> tag tells the browser to download the file in the background and execute it only after the HTML has fully parsed — a best practice when placing <script> tags in <head>.
flowchart LR
A[Browser loads HTML] --> B{Script tag?}
B -- inline --> C[Execute immediately]
B -- external + defer --> D[Download in background]
D --> E[HTML fully parsed]
E --> F[Execute script.js]
Chapter 3: Variables
Variables are named containers for storing data values. Modern JavaScript provides three keywords for declaring them:
let age = 25; // block-scoped; can be reassigned
const name = "Alice"; // block-scoped; cannot be reassigned
var city = "Vizag"; // function-scoped; older style, similar to let
Guidelines:
- Prefer
constby default — it signals that the value will not change. - Use
letwhen you know the variable needs to be reassigned (e.g., a loop counter). - Avoid
varin new code; its function-scoping rules cause subtle bugs thatlet/constprevent.
Chapter 4: Data Types
JavaScript supports several built-in data types:
| Type | Description | Example |
|---|---|---|
| Number | Integer or floating-point | 25, 3.14 |
| String | Text, wrapped in quotes | "Alice", 'hello' |
| Boolean | True or false | true, false |
| Array | Ordered collection of values | ["red", "green"] |
| Object | Collection of key-value pairs | { name: "Alice" } |
let age = 25; // Number
let name = "Alice"; // String
let isStudent = true; // Boolean
let colors = ["red", "green", "blue"]; // Array
let person = { // Object
firstName: "Alice",
lastName: "Smith",
age: 25
};
Arrays are zero-indexed: colors[0] is "red". Object properties are accessed with dot notation (person.firstName) or bracket notation (person["firstName"]).
Chapter 5: Operators
Arithmetic Operators
Used for mathematical calculations:
let a = 10;
let b = 20;
let sum = a + b; // 30 — Addition
let difference = a - b; // -10 — Subtraction
let product = a * b; // 200 — Multiplication
let quotient = a / b; // 0.5 — Division
let remainder = a % b; // 10 — Modulus (remainder after division)
Assignment Operators
Shorthand forms for updating a variable in place:
| Operator | Equivalent |
|---|---|
a = 5 | assign 5 |
a += 3 | a = a + 3 |
a -= 3 | a = a - 3 |
a *= 3 | a = a * 3 |
a /= 3 | a = a / 3 |
Comparison Operators
Return a Boolean (true or false):
let isEqual = a == b; // Equality (value only; loose)
let isIdentical = a === b; // Strict equality (value AND type)
let isNotEqual = a != b; // Inequality (loose)
let isNotIdentical = a !== b; // Strict inequality
// Also available: < > <= >=
=== (strict equality) is always preferred over == because it does not perform type coercion — "5" == 5 is true but "5" === 5 is false.
Logical Operators
Combine boolean expressions:
let isBothTrue = (a < b) && (a > 5); // Logical AND — true only if both sides are true
let isEitherTrue = (a < b) || (a > 15); // Logical OR — true if at least one side is true
let isNotTrue = !(a < b); // Logical NOT — inverts the boolean
Chapter 6: Control Structures
Control structures determine which code runs and how many times.
if…else
Execute a block of code only when a condition is true:
let age = 25;
if (age < 18) {
console.log("You are a minor.");
} else {
console.log("You are an adult.");
}
switch
Cleaner than a long chain of if...else if when testing one variable against many specific values:
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
The break statement exits the switch block. Without it, execution "falls through" to the next case.
for Loop
Repeat a block of code a known number of times:
for (let i = 0; i < 5; i++) {
console.log("Number: " + i);
}
// Prints: Number: 0, Number: 1, Number: 2, Number: 3, Number: 4
The three parts of the for header are: initialiser (let i = 0), condition (i < 5), and update (i++).
while Loop
Repeat a block as long as a condition remains true:
let i = 0;
while (i < 5) {
console.log("Number: " + i);
i++;
}
// Prints: Number: 0, Number: 1, Number: 2, Number: 3, Number: 4
Use while when you do not know in advance how many iterations are needed. Use for when you do.
flowchart TD
A[Start] --> B{Condition true?}
B -- Yes --> C[Execute block]
C --> D[Update / increment]
D --> B
B -- No --> E[Exit loop]
🧪 Try It Yourself
Task: Build a small HTML page with a text input and a button. When the button is clicked, read the value from the input and display a personalised greeting in a paragraph below it.
Success criterion: Typing "Vizag" in the input and clicking the button should display: Hello, Vizag! Welcome to JavaScript. in the paragraph — without a page reload.
Starter snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Greeting App</title>
</head>
<body>
<input type="text" id="cityInput" placeholder="Enter a city name">
<button onclick="showGreeting()">Greet</button>
<p id="output"></p>
<script>
function showGreeting() {
const city = document.getElementById("cityInput").value;
// TODO: build the greeting string and set it as the text of #output
}
</script>
</body>
</html>
Fill in the TODO using document.getElementById("output").textContent = ... and a template literal or string concatenation.
🔍 Checkpoint Quiz
Q1. What is the key difference between == and === in JavaScript?
A) == works only on numbers; === works on all types
B) === checks both value and type; == checks value only (with type coercion)
C) They are identical; === is just an alias
D) == is stricter than ===
Q2. What does the following code print to the console?
let x = 4;
for (let i = 1; i <= x; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
A) 1 2 3 4
B) 2 4
C) 1 3
D) Nothing — the loop condition is never true
Q3. A colleague writes this variable declaration: var total = 0; inside a function, then tries to use total outside the function and gets undefined. What is the most likely cause, and how would you fix it?
A) var is not valid syntax; replace with const
B) var is function-scoped, so total is not accessible outside; declare it with let or const in the outer scope
C) var declarations are always global; the bug must be elsewhere
D) The fix is to add "use strict" at the top of the file
Q4. You are building a "day of the week" feature that maps the numbers 0–6 to day names. Which control structure is most appropriate, and why?
A) while loop — because you do not know how many days there are
B) for loop — because you need to iterate through all seven values sequentially
C) switch statement — because you are testing one variable against a fixed set of known values
D) if...else — it is the only structure that supports default behaviour
A1. B — === (strict equality) compares both value and type without coercion; "5" === 5 is false, while "5" == 5 is true because == coerces the string to a number first.
A2. B — The loop runs for i = 1, 2, 3, 4. The if condition passes only when i % 2 === 0, so only 2 and 4 are logged.
A3. B — var is scoped to the nearest function boundary. Declaring it with let or const at the outer (shared) scope makes it accessible in both places.
A4. C — switch is purpose-built for mapping a single variable to one of several discrete values. It is more readable than seven else if branches and has a built-in default case.
🪞 Recap
- JavaScript is a high-level, browser-executed language that adds behaviour to HTML and CSS pages.
- Scripts can be embedded inline with
<script>tags or loaded from a separate.jsfile using<script src="" defer>. - Variables are declared with
const(preferred),let, orvar; they can hold numbers, strings, booleans, arrays, or objects. - JavaScript operators cover arithmetic (
+,-,*,/,%), assignment (=,+=, etc.), comparison (==,===,!=,!==,<,>,<=,>=), and logical (&&,||,!) operations. - Control flow is managed with
if...else,switch,for, andwhile— each suited to different decision and iteration patterns.
📚 Further Reading
- MDN JavaScript Guide — the source of truth for every JavaScript feature covered here and beyond
- JavaScript.info — The Modern JavaScript Tutorial — a well-structured deep-dive from basics to advanced; free and excellent for beginners
- Eloquent JavaScript (3rd ed.) by Marijn Haverbeke — a free book that builds intuition through exercises; Chapter 1 aligns directly with this lesson
- ⬅️ Previous: CSS Introduction (Internal & External – Inline)
- ➡️ Next: Introduction to PHP and MySQL