Understand JavaScript statements (variables, operators, functions)

21 Programming for the Web – Cambridge AS & A‑Level IT (9626)

1. Overview of Web Development

This topic introduces the fundamentals of creating interactive web pages. It covers:

  • HTML – structure, semantics and accessibility
  • CSS – presentation, layout and responsive design
  • JavaScript – client‑side programming
  • Client‑server model and HTTP basics (methods, status codes, headers, caching)
  • Document Object Model (DOM) and event‑driven programming (including delegation)
  • Web APIs – data fetching, storage, graphics, geolocation, workers, service workers, IndexedDB, CORS
  • Security considerations, accessibility, testing & debugging
  • Version control (Git) and an introduction to Progressive Web Apps (PWAs)

2. HTML – The Mark‑up Language

HTML provides the skeleton of a web page. The syllabus expects knowledge of the following concepts.

2.1 Core Elements & Attributes

  • Structural elements<header>, <nav>, <main>, <section>, <article>, <footer>
  • Textual elements – headings, paragraphs, lists, links, images
  • Form elements<form>, <input>, <select>, <textarea>, validation attributes (required, pattern, min, max)
  • Common attributesid, class, src, href, alt, title, role

2.2 Semantic Mark‑up & Accessibility

  • Use semantic elements (<header>, <nav>, <section>…) to give meaning to page structure.
  • Provide alternative text for images (alt) and ARIA attributes when native semantics are insufficient:
    • role="button", role="dialog", aria‑label, aria‑expanded, aria‑controls
  • Ensure keyboard accessibility:
    • Interactive elements must be reachable with Tab and operable with Enter / Space.
    • Use tabindex="0" only when necessary.
  • Use proper heading order (<h1><h6>) and landmarks (role="main", role="navigation") to aid screen readers.

2.3 Minimal HTML5 Document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>My First Web Page</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>Welcome</h1;
    </header>
    <main id="content" role="main">
        <p id="msg">Hello, world!</p>
    </main>
    <script src="script.js"></script>
</body>
</html>

3. CSS – Styling the Web Page

CSS separates presentation from structure. The syllabus expects knowledge of:

3.1 Selectors

  • Element, class, id, attribute, pseudo‑class (:hover, :focus, :nth-child())
  • Combinators – descendant ( ), child (>), adjacent sibling (+), general sibling (~)

3.2 Box Model & Layout

  • Box model – margin, border, padding, width/height
  • Display – block, inline, inline‑block, flex, grid
  • Positioning – static, relative, absolute, fixed, sticky

3.3 Responsive Design

  • Media queries – breakpoints for different screen widths
  • Mobile‑first approach

3.4 Example CSS

/* styles.css */
body {
    font-family: Arial, sans-serif;
    line-height: 1.5;
    margin: 0;
    padding: 0;
}

#msg {
    color: #0066cc;
    font-size: 1.2rem;
}

/* Responsive example */
@media (max-width: 600px) {
    #msg { font-size: 1rem; }
}

4. Client‑Server Model & HTTP

4.1 Core Components

Component Role in a Web Transaction
Browser (client) Sends an HTTP request, receives the response, renders HTML/CSS/JS.
Web server Receives the request, processes it (static files or server‑side scripts), returns an HTTP response.
HTTP request line GET /index.html HTTP/1.1 – method, resource, protocol.
HTTP response line HTTP/1.1 200 OK – protocol, status code, reason phrase.

4.2 Methods, Status Codes & Headers

  • MethodsGET, POST, PUT, DELETE, HEAD
  • Status codes200 (OK), 201 (Created), 301 (Moved Permanently), 302 (Found), 400 (Bad Request), 401 (Unauthorized), 403 (Forbidden), 404 (Not Found), 500 (Server Error)
  • Common request headers
    • User-Agent – identifies the browser
    • Accept – media types the client can process (e.g., text/html, application/json)
    • Accept-Language – preferred language(s)
    • Cookie – sends stored cookies to the server
  • Common response headers
    • Content-Type – MIME type of the payload (e.g., text/html)
    • Cache-Control – caching directives (max-age=3600, no‑store)
    • ETag – validator for conditional requests
    • Set-Cookie – instructs the browser to store a cookie
  • Caching basics
    • Browser cache respects Cache-Control and Expires headers.
    • Strong validators (ETag, Last-Modified) allow conditional GET requests.

5. JavaScript – Core Language Features

5.1 Statements, Expressions and Code Structure

  • A statement performs an action; it ends with a semicolon (;) – optional but recommended.
  • Multiple statements can be grouped in a block using curly braces { … }.
  • An expression produces a value and can appear inside a statement (e.g., the right‑hand side of an assignment).

5.2 Variables – Declaration, Scope & Best Practice

Keyword Scope Hoisting Re‑assignment
var Function‑scoped (or global if declared outside a function) Hoisted & initialised with undefined Yes
let Block‑scoped Hoisted but in the Temporal Dead Zone until the declaration line Yes
const Block‑scoped Hoisted with TDZ No – the binding is constant; objects/arrays it refers to can still be mutated

Example demonstrating scope and the Temporal Dead Zone:

// global scope
const PI = 3.14159;

function circleArea(r) {
    // console.log(area); // ReferenceError – TDZ
    let area = PI * r * r;
    return area;
}

console.log(circleArea(5)); // 78.53975

5.3 Operators – Categories & Precedence

Category Operators Typical Use
Arithmetic + - * / % ++ -- Numeric calculations
Assignment = += -= *= /= %= **= Store a value in a variable
Comparison == != === !== > < >= <= Produce a Boolean result
Logical && || ! Combine Boolean expressions
String + (concatenation) Join text values
Conditional (ternary) condition ? expr1 : expr2 Inline if‑else
Bitwise & | ^ ~ << >> >>> Low‑level integer manipulation (rare in A‑Level but part of the language)

Use parentheses ( ) to control evaluation order when needed.

5.4 Control Flow

  • if … else, switch – decision making
  • for, while, do…while – loops
  • break, continue – alter loop execution

Example for loop:

for (let i = 1; i <= 5; i++) {
    console.log('Step', i);
}

5.5 Functions – Declaration, Expressions, Arrow Functions & Hoisting

Functions are reusable blocks of code. Three common ways to define them:

// 1. Function declaration – hoisted
function add(x, y) {
    return x + y;
}

// 2. Function expression – not hoisted
const multiply = function (a, b) {
    return a * b;
};

// 3. Arrow function – concise syntax, lexical this
const square = n => n * n;
  • Declarations are hoisted (available before the line they appear).
  • Expressions and arrow functions behave like variables – they are not hoisted.
  • Parameters are local to the function; objects/arrays are passed by reference.
  • If a function reaches the end without return, it returns undefined.

5.6 Error Handling

function parseNumber(str) {
    try {
        const n = Number(str);
        if (isNaN(n)) throw new Error('Not a number');
        return n;
    } catch (err) {
        console.error('Parse error:', err.message);
        return null;
    }
}

5.7 Asynchronous Programming

  • Callback functions – functions passed as arguments to be executed later.
  • Promises – .then(), .catch(), .finally().
  • Async/await – syntactic sugar for promises (ES2017).

Simple fetch example using async/await:

async function loadUser(id) {
    try {
        const response = await fetch(`https://api.example.com/users/${id}`);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const data = await response.json();
        return data;
    } catch (e) {
        console.error(e);
        return null;
    }
}

5.8 Modules (ES6)

// file: mathUtils.js
export function sum(a, b) { return a + b; }
export const PI = 3.14159;

// file: main.js
import { sum, PI } from './mathUtils.js';
console.log(sum(2, 3) * PI);

5.9 The Event Loop & Concurrency Model

  • JavaScript runs on a single thread.
  • The call stack executes synchronous code.
  • Asynchronous callbacks are placed in the task queue and run after the current stack clears.
  • Micro‑tasks (Promises) have priority over macrotasks (e.g., setTimeout, I/O).

6. The Document Object Model (DOM)

6.1 Selecting Nodes

// Single element
const header = document.querySelector('header');

// Multiple elements
const buttons = document.querySelectorAll('.btn');

// Legacy methods
const form = document.getElementById('myForm');

6.2 Manipulating Content & Attributes

const msg = document.getElementById('msg');

// Text content
msg.textContent = 'Welcome to the site!';

// HTML content
msg.innerHTML = '<strong>Hello</strong>';

// Attributes
msg.setAttribute('data-user', 'alice');
msg.dataset.role = 'admin'; // shortcut for data-role

6.3 Adding & Removing Elements

const list = document.querySelector('#todo');
const newItem = document.createElement('li');
newItem.textContent = 'Buy milk';
list.appendChild(newItem);          // add at the end

// Remove
list.removeChild(newItem);

6.4 Event Handling

// Attach a click handler
document.getElementById('btnCalc').addEventListener('click', function (e) {
    e.preventDefault();               // stop default form submit
    const radius = Number(document.getElementById('radius').value);
    const area = Math.PI * radius * radius;
    document.getElementById('result').textContent = area.toFixed(2);
});

6.5 Event Delegation

Instead of attaching a listener to every child, attach one to a common ancestor and use event.target to determine the actual element that triggered the event.

// HTML: <ul id="menu"> … <li class="item">Item 1</li> … </ul>

const menu = document.getElementById('menu');
menu.addEventListener('click', function (e) {
    if (e.target && e.target.matches('li.item')) {
        console.log('Clicked:', e.target.textContent);
    }
});

6.6 Building a Dynamic Table from JSON (Mini‑Project Example)

const data = [
    { name: 'Alice', age: 28, city: 'London' },
    { name: 'Bob',   age: 34, city: 'Manchester' },
    { name: 'Cara',  age: 22, city: 'Bristol' }
];

function buildTable(arr) {
    const table = document.createElement('table');
    const thead = table.createTHead();
    const headerRow = thead.insertRow();
    // create header cells
    Object.keys(arr[0]).forEach(key => {
        const th = document.createElement('th');
        th.textContent = key.charAt(0).toUpperCase() + key.slice(1);
        headerRow.appendChild(th);
    });

    const tbody = table.createTBody();
    arr.forEach(item => {
        const row = tbody.insertRow();
        Object.values(item).forEach(val => {
            const cell = row.insertCell();
            cell.textContent = val;
        });
    });
    return table;
}

document.getElementById('tableContainer').appendChild(buildTable(data));

7. Web APIs – Using Built‑in Browser Features

7.1 Fetch API (Network Requests)

  • Supports promises, can be combined with async/await.
  • Handles CORS – the browser blocks cross‑origin requests unless the server sends appropriate Access-Control-Allow-Origin headers.
// Simple GET request with CORS handling
fetch('https://api.example.com/data', { mode: 'cors' })
    .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
    })
    .then(json => console.log(json))
    .catch(err => console.error('Fetch error:', err));

7.2 Client‑side Storage

  • LocalStorage / SessionStorage – key/value pairs as strings.
  • IndexedDB – low‑level NoSQL database for larger, structured data.
// localStorage example
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme'); // 'dark'

// IndexedDB simple example (open a DB, create an object store, add a record)
const request = indexedDB.open('myDB', 1);
request.onupgradeneeded = e => {
    const db = e.target.result;
    db.createObjectStore('users', { keyPath: 'id' });
};
request.onsuccess = e => {
    const db = e.target.result;
    const tx = db.transaction('users', 'readwrite');
    const store = tx.objectStore('users');
    store.add({ id: 1, name: 'Alice' });
};

7.3 Canvas API (Graphics)

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#0066cc';
ctx.fillRect(10, 10, 150, 100);

7.4 Geolocation API

if ('geolocation' in navigator) {
    navigator.geolocation.getCurrentPosition(pos => {
        console.log('Lat:', pos.coords.latitude, 'Lng:', pos.coords.longitude);
    }, err => console.error(err.message));
}

7.5 Web Workers (Background Threads)

// main.js
const worker = new Worker('worker.js');
worker.postMessage(1000000); // send data to worker
worker.onmessage = e => console.log('Result:', e.data);
// worker.js
self.onmessage = e => {
    const n = e.data;
    // simple heavy calculation
    let sum = 0;
    for (let i = 1; i <= n; i++) sum += i;
    self.postMessage(sum);
};

7.6 Service Workers (Progressive Web Apps)

// Register service worker (main script)
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js')
        .then(reg => console.log('SW registered', reg.scope))
        .catch(err => console.error('SW registration failed', err));
}
// sw.js – simple cache‑first strategy
const CACHE = 'v1';
const ASSETS = [
    '/',
    '/index.html',
    '/styles.css',
    '/script.js'
];

self.addEventListener('install', e => {
    e.waitUntil(
        caches.open(CACHE).then(cache => cache.addAll(ASSETS))
    );
});

self.addEventListener('fetch', e => {
    e.respondWith(
        caches.match(e.request).then(cached => cached || fetch(e.request))
    );
});

7.7 CORS (Cross‑Origin Resource Sharing)

  • Browsers enforce the Same‑Origin Policy; a script can only fetch resources from the same origin unless the server includes Access-Control-Allow-Origin in its response.
  • When a cross‑origin request is made, the browser first sends a pre‑flight OPTIONS request if the request uses non‑simple methods or custom headers.

8. Security Basics for Web Pages

Examiners expect awareness of common client‑side threats and mitigation techniques.

Threat Typical Attack Mitigation (client‑side)
Cross‑Site Scripting (XSS) Injecting malicious script into page content Escape user input, use textContent instead of innerHTML, set a Content‑Security‑Policy header, validate input on the server.
Cross‑Site Request Forgery (CSRF) Forcing a logged‑in user to perform unwanted actions Include anti‑CSRF tokens in forms, use SameSite cookies, verify the Origin header on the server.
Clickjacking Embedding a page in a hidden frame to trick users into clicking Send X‑Frame‑Options: SAMEORIGIN or Content‑Security‑Policy: frame‑ancestors 'self' header.
Man‑in‑the‑Middle (MITM) Intercepting and modifying traffic between client and server Serve pages over HTTPS, use HSTS, avoid mixed content.

9. Summary Checklist for the Exam

  • Write valid semantic HTML and include at least one ARIA attribute.
  • Explain the box model and give a CSS rule that makes an element responsive.
  • Identify HTTP request methods, status codes, and three common request/response headers.
  • Declare variables with let and const, describe hoisting and the Temporal Dead Zone.
  • Show the precedence of an expression using parentheses.
  • Write a for loop and an if…else statement.
  • Define a function using a declaration and an arrow function; explain hoisting.
  • Demonstrate error handling with try…catch.
  • Fetch JSON data using async/await and handle a possible HTTP error.
  • Select a DOM element, change its text, add a CSS class, and remove it later.
  • Implement event delegation for a list of buttons.
  • Build a table dynamically from an array of objects.
  • Store a value in localStorage and retrieve it; outline how IndexedDB differs.
  • Register a service worker that caches the core assets.
  • Identify at least two client‑side security threats and the corresponding mitigation.

Create an account or Login to take a Quiz

33 views
0 improvement suggestions

Log in to suggest improvements to this note.