Learning Objectives
- Understand the role of JavaScript in web pages and distinguish client vs server JS.
- Write basic JS: variables, types, operators, control flow and functions.
- Select and modify DOM elements and respond to user events.
- Debug code using console and DevTools.
- Build a small interactive demo (Light/Dark Mode Switcher) and test it in the playground.
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,constor (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:
()=>{}; lexicalthis. - 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.
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
- Create
counter.htmlwith a button that increments a number and saves it tolocalStorage. - Display the stored count on page load.
Lab 2 — Form validation and UI feedback
- Attach an event listener to your contact form to prevent submission and validate fields in JS.
- Show inline error messages and focus the first invalid field.
Lab 3 — Event delegation
- Create a list of items and attach a single click listener to the parent that handles clicks on any child item using
event.target. - Explain how this reduces listeners and supports dynamic items.
Advanced Tips (mastery)
- Organize code into small, single-purpose functions for readability and testing.
- Avoid mutating DOM excessively — batch updates or use document fragments for large changes.
- Use descriptive variable names and keep functions under ~25 lines for maintainability.
"In all your getting, get understanding." — Proverbs 4:7. Practice patiently and test your assumptions — code is solved step-by-step.