Topic 16 of 26 · UI Designer

Topic 1 : Introduction to JavaScript

Lesson TL;DRTopic 1: Introduction to JavaScript 📖 5 min read · 🎯 beginner · 🧭 Prerequisites: cssintroductioninternalexternalinlinetaskforminternal Why this matters Up until now, you've built pages that look go...
5 min read·beginner·javascript · web-development · variables · data-types

Topic 1: Introduction to JavaScript

📖 5 min read · 🎯 beginner · 🧭 Prerequisites: css-introduction-internal-external-inline-task-form-internal

Why this matters

Up until now, you've built pages that look good — HTML gave them structure, CSS made them beautiful. But here's the thing — they don't do anything yet. Click a button? Nothing happens. Fill a form? It just sits there. That's where JavaScript comes in. JavaScript is what makes a webpage actually respond to you — it's the difference between a photograph of a light switch and a real one. By the end of this lesson, your buttons will actually work.

What You'll Learn

  • Understand what JavaScript is and why it exists alongside HTML and CSS
  • Add JavaScript to a webpage both inline and via an external file
  • Declare variables using let, const, and var and work with core data types
  • Write expressions with arithmetic, assignment, comparison, and logical operators
  • Control program flow with if...else, switch, for, and while structures

The Analogy

Think of a website as a stage production. HTML is the set — the walls, the furniture, the props. CSS is the lighting and costume design — it determines how everything looks. JavaScript is the actors: they move, react to the audience, remember their lines, and change the scene depending on what happens. Without JavaScript, the curtain rises on a beautiful but completely motionless tableau. With it, the show actually runs.

Chapter 1: What is JavaScript?

JavaScript is a versatile, high-level programming language that is essential for web development. Unlike HTML and CSS, which are declarative (you describe what you want), JavaScript is imperative — you describe what to do step by step.

Key characteristics:

  • Runs in the browser — no installation needed by the end user; every modern browser ships a JavaScript engine.
  • Interpreted — code is executed line by line at runtime, not compiled ahead of time.
  • Dynamic — variables can hold any type of value; types are determined at runtime.
  • Event-driven — JavaScript listens for user actions (clicks, key presses, scrolls) and responds to them.

The three-layer model of the web:

LayerTechnologyRole
StructureHTMLContent and semantics
PresentationCSSVisual styling
BehaviourJavaScriptInteractivity and logic

Chapter 2: Adding JavaScript to a Web Page

There are two main ways to include JavaScript in an HTML document.

1. Inline JavaScript

Inline JavaScript lives inside a <script> tag directly within the HTML file. This is convenient for small snippets and quick prototypes.

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

The <script> tag is placed just before </body> so that the HTML loads and renders before the script runs — preventing blank-page flashes.

2. External JavaScript

For anything beyond a few lines, keep JavaScript in a separate .js file and link to it from HTML. This keeps concerns separated and allows the browser to cache the script.

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: "Download this file in the background, but wait until the HTML is fully parsed before executing it." This is why the <script> tag can safely go in <head> when defer is present.

Chapter 3: JavaScript Basics

Variables

Variables are named containers for storing data values. Modern JavaScript offers three declaration keywords:

let age = 25;           // Can be reassigned; block-scoped
const name = "Alice";   // Cannot be reassigned after declaration; block-scoped
var city = "Vizag";  // Older style; function-scoped; avoid in new code
  • Prefer const by default.
  • Use let when you know the value will change.
  • Avoid var in new code — its function-scoping rules cause subtle bugs.

Data Types

JavaScript supports the following core data types:

  • Number — integer or floating-point values
  • String — text, wrapped in single or double quotes
  • Booleantrue or false
  • Array — ordered, zero-indexed collection of values
  • Object — unordered collection of key-value pairs
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
};

Operators

JavaScript provides four main categories of operators:

Arithmetic Operators+, -, *, /, %

Assignment Operators=, +=, -=, *=, /=

Comparison Operators==, ===, !=, !==, <, >, <=, >=

Logical Operators&&, ||, !

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

let isEqual       = a == b;   // false — Equality (loose)
let isIdentical   = a === b;  // false — Strict equality (type + value)
let isNotEqual    = a != b;   // true  — Inequality
let isNotIdentical = a !== b; // true  — Strict inequality

let isBothTrue   = (a < b) && (a > 5);   // true — Logical AND
let isEitherTrue = (a < b) || (a > 15);  // true — Logical OR
let isNotTrue    = !(a < b);             // false — Logical NOT

Prefer === over ==. The strict equality operator checks both value and type, which prevents unexpected coercions like 0 == false evaluating to true.

Control Structures

Control structures direct the order in which statements execute.

if...else — conditional branching

let age = 25;

if (age < 18) {
    console.log("You are a minor.");
} else {
    console.log("You are an adult.");
}

switch — multiple discrete conditions

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");
}

for — repeat a fixed number of times

for (let i = 0; i < 5; i++) {
    console.log("Number: " + i);
}

while — repeat while a condition holds

let i = 0;

while (i < 5) {
    console.log("Number: " + i);
    i++;
}

Both loops above print Number: 0 through Number: 4. The for loop is preferred when you know the iteration count up front; while is preferred when the stop condition is determined by runtime state.

flowchart TD
    A[Start] --> B{Condition true?}
    B -- Yes --> C[Execute loop body]
    C --> D[Update counter]
    D --> B
    B -- No --> E[Exit loop]

🧪 Try It Yourself

Task: Build a simple age-checker page that reads a number from a text input and logs a message to the browser console.

Success criterion: Opening the browser console (F12 → Console) and clicking the button should print either "You are a minor." or "You are an adult." depending on what number was typed.

Starter snippet — save as age-check.html and open in a browser:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Age Checker</title>
</head>
<body>
    <h1>Age Checker</h1>
    <input type="number" id="ageInput" placeholder="Enter your age" />
    <button onclick="checkAge()">Check</button>

    <script>
        function checkAge() {
            const age = Number(document.getElementById("ageInput").value);

            if (age < 18) {
                console.log("You are a minor.");
            } else {
                console.log("You are an adult.");
            }
        }
    </script>
</body>
</html>

Stretch goal: Add a third branch for ages over 65 that logs "You are a senior.".

🔍 Checkpoint Quiz

Q1. What is the key difference between == and === in JavaScript?

A) == only works with numbers; === works with all types
B) === checks both value and type; == checks value only and coerces types
C) They are identical — === is just a style preference
D) === is used inside switch statements; == is used inside if statements


Q2. Given the following code, what is printed to the console?

let x = 0;
while (x < 3) {
    console.log(x);
    x++;
}

A) 0 1 2 3
B) 1 2 3
C) 0 1 2
D) Nothing — the loop never runs


Q3. Which snippet correctly declares a constant called siteTitle holding the string "Vizag", and then attempts (incorrectly) to reassign it?

// Snippet A
const siteTitle = "Vizag";
siteTitle = "New City";

// Snippet B
let siteTitle = "Vizag";
siteTitle = "New City";

What happens when Snippet A runs?

A) It silently overwrites siteTitle with "New City"
B) It throws a TypeError because const variables cannot be reassigned
C) It declares a new variable called siteTitle in a different scope
D) It works fine because strings are immutable anyway


Q4. You want a button on your page to call a function showMenu() that lives in an external file called nav.js. Write the two pieces of HTML you need: the <script> tag (using defer) and the <button> tag.

A1. B — === (strict equality) checks both value and type. == performs type coercion first, which can produce surprising results like 0 == false being true. Always prefer === in new code.

A2. C — The loop starts at x = 0 and runs while x < 3, printing 0, then 1, then 2. After printing 2, x becomes 3, the condition fails, and the loop exits.

A3. B — Attempting to reassign a const variable throws a TypeError: Assignment to constant variable. at runtime. Snippet B with let would work correctly.

A4.

<script src="nav.js" defer></script>
<button onclick="showMenu()">Menu</button>

The defer attribute ensures nav.js is fully loaded before it can be called by the button click.

🪞 Recap

  • JavaScript is the behaviour layer of the web — it makes HTML pages interactive and dynamic.
  • You can embed JavaScript inline with a <script> tag or link an external .js file using src and defer.
  • Variables are declared with const (immutable binding), let (reassignable, block-scoped), or var (legacy, avoid).
  • JavaScript's core data types are Number, String, Boolean, Array, and Object.
  • Arithmetic, assignment, comparison, and logical operators let you compute and compare values; always prefer === over ==.
  • Control structures — if...else, switch, for, while — direct the flow of your program based on conditions and iteration.

📚 Further Reading

Like this topic? It’s one of 26 in UI Designer.

Block your seat for ₹2,500 and join the next cohort.