G.O.C
· JavaScript for Web Development
Teacher mode
◐ Theme
Present
◀ Prev
Next ▶
+
−
Fit
Expand all
Collapse
# JavaScript for Web Development ## 1. JavaScript & The Browser ### What JavaScript is JavaScript makes webpages interactive. HTML = structure, CSS = appearance, JavaScript = behavior. !Show a button that exists (HTML), looks good (CSS), then does something on click (JS). ### Adding JavaScript to HTML Put a script tag at the end of the body so the page elements exist before your code runs. > Example: a button that changes a heading. > const button = document.getElementById("changeButton");\nconst message = document.getElementById("message");\nbutton.addEventListener("click", function () {\n message.textContent = "You just used JavaScript!";\n}); !Challenge: change the message to "Welcome to my website!" and make it change on every click. ### console.log() The browser console is one of your most important tools. Open it in Developer Tools. > console.log("Hello World");\nconsole.log("Name:", "John"); ### Statements A statement is one instruction. The browser runs statements from top to bottom. ### Comments Comments are notes for humans; JavaScript ignores them. > // a single-line comment ## 2. Variables & Data ### let Variables store information. Use let when the value may change. > let score = 10;\nscore = 20; ### const Use const when the variable should not be reassigned. > const school = "ABC Academy"; ### Strings Text in quotes. Join strings with +. > const fullName = firstName + " " + lastName; ### Numbers Numbers are used for maths. Input values are text, so convert them first. > const total = Number(priceInput.value) * Number(quantityInput.value); !Common mistake: forgetting Number() so "2" + "3" becomes "23". ### Booleans true or false. They power decisions. > const inStock = true; ### null / undefined undefined = a variable with no value yet. null = an intentionally empty value. ### Template literals Backticks let you put variables inside text with ${ }. > const fullName = `${firstName} ${lastName}`; ## 3. Operators & Decisions ### Arithmetic > + - * / % ** % gives the remainder; ** is "to the power of". ### Comparison > === !== > < >= <= ### Logical operators > && (and) || (or) ! (not) ### if / else > if (age >= 18) {\n console.log("Adult");\n} else {\n console.log("Minor");\n} !Show an Age Checker: input, Check button, result text. ### else if Chain several conditions; the first true one runs. > if (score >= 70) { grade = "A"; } else if (score >= 60) { grade = "B"; } else { grade = "F"; } ### Ternary operator A short if/else in one line. > const label = age >= 18 ? "Adult" : "Minor"; ## 4. Functions ### Creating functions Functions package reusable behavior. Define once, call many times. > function greet() {\n console.log("Hello");\n}\ngreet(); ### Parameters > function greet(name) {\n console.log(`Hello ${name}`);\n}\ngreet("John"); ### Return values > function add(a, b) {\n return a + b;\n}\nconst result = add(5, 3); ### Arrow functions > const add = (a, b) => a + b; ### Practical functions Example from the Tip Calculator: > function calculateTip(bill, percentage) {\n return bill * (percentage / 100);\n} ## 5. The DOM ### What the DOM is DOM = Document Object Model. It is how JavaScript sees and changes your HTML. !This is one of the most important modules in the course. ### Selecting elements > document.getElementById("title");\ndocument.querySelector(".card");\ndocument.querySelectorAll(".item"); ### Changing text > const title = document.querySelector("h1");\ntitle.textContent = "Hello!"; ### Changing HTML innerHTML inserts HTML markup into an element. > container.innerHTML = `
${product.name}
`; ### Changing styles > element.style.color = "red"; For bigger apps, prefer classes. ### Classes > element.classList.add("active");\nelement.classList.remove("active");\nelement.classList.toggle("active"); Pattern: user action → JavaScript changes a class → CSS changes appearance (Dark Mode example). ### Creating elements > const li = document.createElement("li");\nli.textContent = "New task";\nlist.appendChild(li); ## 6. Events ### click > button.addEventListener("click", function () {\n message.textContent = "Clicked!";\n}); ### input Fires on every keystroke. Example: live character counter. > message.addEventListener("input", function () {\n count.textContent = message.value.length;\n}); ### submit Fires when a form is submitted. See Forms & Validation. ### change Fires when a select, checkbox or input value is committed. ### Keyboard events > keydown keyup ### Event listeners The pattern for every event: > element.addEventListener("event", function () {\n\n}); ## 7. Forms & Validation ### Reading form values > const name = nameInput.value; ### Preventing default behavior > form.addEventListener("submit", function (event) {\n event.preventDefault();\n}); ### Validation Check the values before accepting them. > if (password.value.length < 6) { return; } ### Error messages Tell the user what is wrong, in the page. > message.textContent = "Password must be at least 6 characters."; ### Form feedback Confirm success too. > message.textContent = "Login form is valid."; ## 8. Arrays & Objects ### Arrays > const fruits = ["Apple", "Banana", "Orange"];\nfruits[0];\nfruits.push("Mango");\nfruits.pop(); ### Objects > const product = { id: 1, name: "Laptop", price: 500000, inStock: true };\nproduct.name; ### Array methods > push() pop() shift() unshift() includes() indexOf() slice() splice() map() filter() find() forEach() ### map() Makes a new array by transforming each item. > const doubled = [1, 2, 3, 4].map(n => n * 2); // [2, 4, 6, 8] ### filter() Keeps only items that pass a test. > const result = [10, 20, 30, 40].filter(n => n >= 30); // [30, 40] ### find() Returns the first matching item. > const laptop = products.find(p => p.name === "Laptop"); ### Practical data An array of objects is how real websites store data (students, products, expenses). > const students = [{ name: "John", age: 20 }, { name: "Mary", age: 22 }]; ## 9. Loops & Rendering Data ### for > for (let i = 0; i < 5; i++) {\n console.log(i);\n} ### for...of > for (const student of students) {\n console.log(student);\n} ### forEach() > students.forEach(function (student) {\n console.log(student.name);\n}); ### Rendering lists Big idea: hard-coded HTML → JavaScript data → JavaScript generates HTML. > students.forEach(function (s) {\n studentList.innerHTML += `
${s.name}
`;\n}); !Emphasize this idea heavily. ### Dynamic cards > container.innerHTML = `
${product.name}
₦${product.price.toLocaleString()}
`; ## 10. Browser Storage ### localStorage Data survives a page refresh. > localStorage.setItem("name", "John");\nconst name = localStorage.getItem("name");\nlocalStorage.removeItem("name");\nlocalStorage.clear(); ### sessionStorage Works like localStorage but clears when the tab closes. ### JSON.stringify() Storage holds only strings, so convert objects first. > localStorage.setItem("user", JSON.stringify(user)); ### JSON.parse() > const user = JSON.parse(localStorage.getItem("user")); ## 11. Modern JavaScript ### Destructuring > const { name, age } = student; ### Spread operator > const second = [...first, 4, 5];\nconst updatedUser = { ...user, age: 20 }; ### Rest parameters Collect extra arguments into an array. > function total(...numbers) { return numbers.length; } ### Optional chaining > console.log(user?.address?.city); ### Nullish coalescing Use a default only when the value is null or undefined. > const city = user?.address?.city ?? "Unknown"; ### Modules Split code into files with export and import. > export function add(a, b) { return a + b; }\nimport { add } from "./math.js"; ## 12. Asynchronous JavaScript ### setTimeout() Some things take time; JavaScript keeps going meanwhile. > console.log("Start");\nsetTimeout(function () {\n console.log("Finished");\n}, 2000);\nconsole.log("End"); ### Callbacks A function passed to another function to run later (like the one above). ### Promises > const promise = new Promise(function (resolve, reject) {\n resolve("Success!");\n});\npromise.then(function (result) {\n console.log(result);\n}); ### async / await The form students should be able to read and write. > async function getData() {\n const response = await fetch("https://example.com");\n const data = await response.json();\n console.log(data);\n} ### fetch() Requests data from a server. Returns a promise. ### APIs An API lets your website talk to another service: website → fetch() → API → JSON → JavaScript → HTML. ## 13. Working With APIs ### HTTP basics The browser sends a request; the server sends back a response with a status. response.ok is true for success. ### GET requests > const response = await fetch("https://jsonplaceholder.typicode.com/users"); ### JSON > const users = await response.json(); ### Loading states Show feedback while waiting. > usersContainer.textContent = "Loading..."; ### Error handling > try {\n if (!response.ok) throw new Error("Could not load users.");\n} catch (error) {\n usersContainer.textContent = "Something went wrong.";\n console.error(error);\n} ### Displaying API data > users.forEach(function (user) {\n usersContainer.innerHTML += `
${user.name}
${user.email}
`;\n}); ## 14. Debugging ### console > console.log() console.error() console.table(users) ### Reading errors Read the message, find the file, find the line number. ### Breakpoints In DevTools > Sources, click a line number to pause there and inspect values. Other tabs: Elements, Console, Network, Application. ### Common mistakes Typos in IDs, forgetting Number(), script loaded before the elements exist, = instead of ===. ### Debugging workflow Something breaks → read the error → find file and line → check the values → fix → test again. ## 15. Real Projects ### Calculator Combines variables, numbers, functions, events, DOM and conditions. #### Version 1: addition only #### Version 2: all four operations #### Version 3: decimals #### Version 4: Clear button #### Version 5: keyboard support #### Version 6: better UI ### To-do app Features: add, display, complete, delete, store tasks. #### Add and render tasks Use an array of objects with id, text, completed. > todos.push({ id: Date.now(), text: text, completed: false }); #### Complete and delete #### Save with localStorage ### Quiz app Question → options → user selects → check answer → update score → next question → final score. > const questions = [{ question: "Which keyword creates a constant?", options: ["var", "let", "const"], answer: "const" }]; ### Expense tracker Add and delete expenses, show a total, filter by category, save with localStorage. > const total = expenses.reduce(function (sum, e) { return sum + e.amount; }, 0); ### Product filter Product cards, search, category filter, price filter, sort by price. > products.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase())); ### Weather app Fetch weather JSON from an API and display it, with loading and error states. ### Final project Build a complete web application. Options: Student Management System, Mini E-commerce, School Portal, Personal Finance Dashboard. !Recommended: School Portal, because students understand the problem domain immediately.