ARISE AFRICA NETWORK VOCATIONAL COURSE (AAN)

Module 6 — JavaScript Essentials: Syntax, DOM & Events

Learning Objectives

Key Terms & Definitions

JavaScript (JS)
A programming language that runs in browsers (client-side) and on servers (Node.js).
Variable
A named storage for values, declared with let, const or (legacy) var.
Data types
Primitive types: string, number, boolean, null, undefined, symbol; and complex: object, array.
Operator
Symbols that perform operations: arithmetic (+ - * /), comparison (===, <), logical (&&, ||).
Function
A block of code that can be called with arguments and may return a value.
Expression
Any valid unit of code that resolves to a value.
Statement
An instruction that performs an action but does not necessarily produce a value.
Scope
The accessibility of variables: global, function, block scope.
Hoisting
Behavior where declarations are moved to the top of their scope (var/function declarations).
Array
An ordered list of values with zero-based indexes.
Object
Key/value data structure used to model entities.
DOM
Document Object Model — the browser's representation of HTML elements as objects.
Element selection
Methods: getElementById, querySelector, querySelectorAll.
Event
Actions like clicks, inputs, submit, keypress that code can listen for and handle.
Event listener
A function attached to an element to run when an event occurs (addEventListener).
Callback
A function passed into another function to be called later (e.g., event handler).
Arrow function
Shorter syntax for functions: ()=>{}; lexical this.
this
Contextual keyword referencing the current object or calling context.
Promise
An object representing eventual completion/failure of asynchronous operations (covered later).
JSON
JavaScript Object Notation — text format for structured data exchange.
localStorage
Browser storage API for small key/value pairs persistent across sessions.
Strict mode
'use strict' enforces stricter parsing and error handling.
Console
Developer tool for logging and debugging (console.log, console.error).
Event delegation
Attaching a single listener to a parent element to handle events from children.
Debounce/Throttle
Techniques to limit how often a function runs (performance).
Mutation
Changing DOM or data structures directly (vs creating new copies).
Immutability
Pattern of not changing existing data — helpful in predictable code.

Detailed Theory — JavaScript Essentials (concepts, examples, best practices)

6.1 What is JavaScript and where it runs?

JavaScript is the language that adds interactivity to web pages. It runs in the browser and can also run on servers via Node.js. In the browser, JS manipulates the DOM, listens for events, and communicates with servers using HTTP.

6.2 Adding JS to a page

Two common ways: inline script in HTML head/body using <script> or linking external files with <script src="js/app.js" defer></script>. Use defer or place scripts at the end of body so DOM is available.

6.3 Variables, types and basic operators

const name = 'AAN';
let count = 0; // mutable
count += 1;
const isActive = true;

Prefer const for values that don't change and let for variables that will be reassigned. Avoid var.

6.4 Control flow: conditionals and loops

if(score >= 70){ console.log('Passed'); } else { console.log('Try again'); }
for(let i=0;i<5;i++){ console.log(i); }

6.5 Functions and reuse

Functions encapsulate code and make it reusable. Use named functions for stack traces and arrow functions for short callbacks:

function add(a,b){ return a+b; }
const greet = name => `Hello ${name}`;

6.6 The DOM — selecting & manipulating elements

Select elements with document.querySelector or getElementById and modify properties like textContent, innerHTML, and classList.

const title = document.querySelector('h1');
title.textContent = 'New title';

6.7 Events & event listeners

Attach listeners to handle user actions:

button.addEventListener('click', function(event){
  console.log('clicked', event);
});

Use event delegation for lists and dynamic content.

6.8 Manipulating classes & styles

element.classList.add('active');
element.classList.toggle('hidden');

6.9 localStorage basics

localStorage.setItem('name','AAN');
const name = localStorage.getItem('name');

6.10 Debugging tips

Use console.log, set breakpoints in Sources panel, and inspect variables and call stacks. Read error messages carefully — they often show line numbers and hints.

Interactive Demo — Light/Dark Mode Switcher

The demo below demonstrates selecting elements, listening to events, toggling classes and saving user preference to localStorage. Try toggling the theme and then reload the preview to see persistence.

Demo includes a small style sheet and JS. You can view and edit both in the playground below.

Live Playground — HTML + JS (Visual Output)

Edit the code on the left (HTML & JS) and press Run. The preview shows live visual output. The demo includes a theme switcher and a click counter for practice.

Practical Labs — Step-by-step

Lab 1 — Click Counter & Persistence

  1. Create counter.html with a button that increments a number and saves it to localStorage.
  2. Display the stored count on page load.

Lab 2 — Form validation and UI feedback

  1. Attach an event listener to your contact form to prevent submission and validate fields in JS.
  2. Show inline error messages and focus the first invalid field.

Lab 3 — Event delegation

  1. Create a list of items and attach a single click listener to the parent that handles clicks on any child item using event.target.
  2. Explain how this reduces listeners and supports dynamic items.

Advanced Tips (mastery)

Faith Corner

"In all your getting, get understanding." — Proverbs 4:7. Practice patiently and test your assumptions — code is solved step-by-step.

Knowledge Check — 5 Questions

Q1. Which keyword creates an immutable binding (cannot be reassigned)?


Q2. Which method selects the first matching element using a CSS selector?


Q3. How do you add a click listener to a button?


Q4. Which API stores small key/value pairs in the browser that persist across sessions?


Q5. Which is a safe way to update text inside an element to avoid HTML injection?