optional · CSS study notes
13. JavaScript (Functionalities, Events, Variables, Operators)
CSS Optional — Paper-II, Section-B · P-II.VI.13 · Syllabus names four sub-items: Functionalities, Events, Variables, Operators. Expect "write a script", "predict the output" and "explain events" questions.
1. What Is JavaScript?
- A high-level, interpreted/JIT-compiled, dynamically typed, multi-paradigm (event-driven, functional, object-oriented, prototype-based) scripting language — the programming language of the web, alongside HTML (structure) and CSS (presentation).
- Created by Brendan Eich at Netscape in 1995; standardized as ECMAScript by Ecma International (TC39). Major update ES6/ES2015 (let/const, arrow functions, classes, promises, modules); yearly releases since.
- Runs in the browser's JS engine (V8 in Chrome, SpiderMonkey in Firefox) and on servers via Node.js (2009).
- JavaScript ≠ Java — different languages; the name was a marketing choice.
2. Functionalities (what JavaScript can do)
- Client-side form validation before submission (instant feedback, fewer server round trips).
- DOM manipulation — change content, structure and style of a page without reloading.
- Event handling — respond to clicks, key presses, scrolling, form submission.
- Asynchronous communication (AJAX / fetch) — load data from servers in the background.
- Animations and interactive UI — sliders, menus, modals, charts.
- Browser storage — cookies, localStorage, sessionStorage.
- Browser APIs — geolocation, canvas drawing, audio/video control, notifications.
- Single-page applications with frameworks (React, Angular, Vue).
- Server-side programming with Node.js; mobile apps (React Native).
3. Adding JavaScript to a Page
<!-- inline event attribute -->
<button onclick="alert('Hi')">Click</button>
<!-- internal -->
<script> console.log("Loaded"); </script>
<!-- external (best practice); defer = run after HTML is parsed -->
<script src="app.js" defer></script>
4. Variables
| Keyword | Scope | Re-declare? | Re-assign? | Hoisting |
|---|---|---|---|---|
| var (old) | Function scope | Yes | Yes | Hoisted, initialized as undefined |
| let (ES6) | Block scope | No | Yes | Hoisted but in "temporal dead zone" (error if used before declaration) |
| const (ES6) | Block scope | No | No (but object contents can change) | Same as let |
Rules for names: start with a letter, _ or $; case-sensitive; no reserved words.
Data types: primitives — string, number, bigint, boolean, undefined, null, symbol; and object (objects, arrays, functions). Dynamic typing: let x = 5; x = "five"; is legal.
let name = "Awais"; // string
const PI = 3.14; // number
let isAdmin = false; // boolean
let marks = [80, 75, 92]; // array (object)
let student = { name: "Ali", age: 21 }; // object
console.log(typeof marks); // "object"
console.log(typeof null); // "object" (a historic bug)
5. Operators
| Category | Operators |
|---|---|
| Arithmetic | • - / % • ++ -- |
| Assignment | = += -= *= /= %= |
| Comparison | == (loose, converts types), === (strict, type + value), !=, !==, <, >, <=, >= |
| Logical | && (AND), |
| String | • (concatenation), template literals with backticks |
| Conditional (ternary) | condition ? a : b |
| Type | typeof, instanceof |
| Modern | ?? (nullish coalescing), ?. (optional chaining), ... (spread/rest) |
Output-prediction examples (favourite exam material)
console.log("5" + 3); // "53" (+ with a string concatenates)
console.log("5" - 3); // 2 (- converts to number)
console.log(5 == "5"); // true (loose equality converts)
console.log(5 === "5"); // false (different types)
console.log(null == undefined); // true
console.log(NaN === NaN); // false
console.log(10 % 3); // 1
console.log(2 ** 3); // 8
let a = 5; console.log(a++ + ++a); // 5 + 7 = 12
console.log(0.1 + 0.2 === 0.3); // false (floating point)
console.log(true + 1); // 2
6. Functions
function add(a, b) { return a + b; } // declaration
const sub = function (a, b) { return a - b; }; // expression
const mul = (a, b) => a * b; // arrow function (ES6)
7. Events
An event is an action or occurrence (user or browser) that JavaScript can respond to with an event handler/listener.
| Category | Events |
|---|---|
| Mouse | click, dblclick, mouseover, mouseout, mousedown, mouseup, contextmenu |
| Keyboard | keydown, keyup (keypress is deprecated) |
| Form | submit, change, input, focus, blur, reset |
| Window/document | load, DOMContentLoaded, resize, scroll, unload/beforeunload |
| Touch/media | touchstart, touchend, play, pause, ended |
Three ways to handle events
// 1. HTML attribute: <button onclick="greet()">
// 2. DOM property (only one handler per event)
btn.onclick = greet;
// 3. addEventListener (best: many handlers, capture option, removable)
btn.addEventListener("click", greet);
Event propagation: capturing phase (window → target), target phase, bubbling phase (target → window). event.stopPropagation() stops propagation; event.preventDefault() cancels the default action (e.g. form submission, link navigation).
Event delegation: attach one listener to a parent and use event.target to handle clicks on many children (efficient for dynamic lists).
8. Complete Example — Form Validation
<form id="reg">
<input id="email" placeholder="Email">
<input id="age" type="number" placeholder="Age">
<button type="submit">Register</button>
<p id="msg"></p>
</form>
<script>
document.getElementById("reg").addEventListener("submit", function (e) {
const email = document.getElementById("email").value.trim();
const age = Number(document.getElementById("age").value);
const msg = document.getElementById("msg");
if (!email.includes("@")) {
e.preventDefault(); // stop submission
msg.textContent = "Enter a valid email";
} else if (age < 18) {
e.preventDefault();
msg.textContent = "You must be 18 or older";
}
});
</script>
9. Asynchronous JavaScript (brief)
- JavaScript is single-threaded with an event loop; long tasks are handled asynchronously.
- Evolution: callbacks → Promises → async/await.
async function loadUsers() {
const res = await fetch("https://api.example.com/users");
const users = await res.json();
console.log(users.length);
}
🎯 CSS Exam Angle
Write short, correct code: validation scripts, a button click that changes text, a loop summing an array. For theory, use the var/let/const table, the operator table with == vs === examples, and the three event-handling methods plus bubbling.
⚠️ MCQ Traps
typeof nullis "object";typeof []is "object";typeof function(){}is "function"."5" + 3 = "53"but"5" - 3 = 2.==converts types;===does not — always prefer===.constprevents reassignment, not mutation of object contents.let/constare block-scoped;varis function-scoped.- Events bubble from the target up by default.
- JavaScript is not Java.
✅ Self-Check (with Answers)
Q1. Predict: let x = "10"; let y = 5; console.log(x + y, x - y, x * y);
Ans: 105 5 50 — + concatenates when one operand is a string; - and * convert "10" to a number.
Q2. What is the output of for (var i = 0; i < 3; i++) {} console.log(i); and would it change with let?
Ans: Prints 3, because var is function-scoped and visible after the loop. With let it throws a ReferenceError, since i is block-scoped to the loop.
Q3. Write JavaScript that changes a paragraph's text to "Clicked!" when a button with id "btn" is clicked.
Ans: document.getElementById("btn").addEventListener("click", () => { document.getElementById("para").textContent = "Clicked!"; });
Q4. Differentiate event bubbling and capturing.
Ans: Capturing travels from the outermost element down to the target; bubbling travels from the target back up to the outermost ancestors. Listeners run in the bubbling phase by default; passing true (or {capture: true}) to addEventListener uses capturing.
Q5. What do preventDefault() and stopPropagation() do?
Ans: preventDefault() cancels the browser's default action (e.g. submitting a form, following a link); stopPropagation() stops the event from travelling to other elements in the capture/bubble path.
Q6. Write a function that returns the average of an array of marks.
Ans: function avg(arr) { let sum = 0; for (let m of arr) sum += m; return arr.length ? sum / arr.length : 0; } — e.g. avg([80, 75, 92]) = 82.33.
📜 Past-Paper Questions & MCQs (CSS 2016–2026)
2022 · Paper-II · Q7(b) and 2023 · Paper-II · Q8(c) · 6 and 4 marks
Q. Write the jQuery code to slide elements up and down, and to fade elements in and out of visibility. Use HTML, CSS and jQuery.
Ans.
<!DOCTYPE html>
<html>
<head>
<style>
#panel { width: 250px; height: 100px; background: #9cf; padding: 10px; display: none; }
button { margin: 4px; }
</style>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("#down").click(function () { $("#panel").slideDown("slow"); }); // slide down
$("#up").click(function () { $("#panel").slideUp("slow"); }); // slide up
$("#in").click(function () { $("#panel").fadeIn(1000); }); // fade in
$("#out").click(function () { $("#panel").fadeOut(1000); }); // fade out
$("#toggle").click(function () { $("#panel").slideToggle(); }); // up/down in one button
});
</script>
</head>
<body>
<button id="down">Slide Down</button> <button id="up">Slide Up</button>
<button id="in">Fade In</button> <button id="out">Fade Out</button>
<button id="toggle">Slide Toggle</button>
<div id="panel">Hello! I slide and fade.</div>
</body>
</html>
slideDown()andslideUp()animate the height.fadeIn()andfadeOut()animate the opacity. The argument is the speed ("slow", "fast" or milliseconds).
2024 · Paper-II · Q8(a) · 7 marks
Q. Develop a numerical comparison between client-side functionalities implemented using different JavaScript patterns. Discuss how these patterns impact code maintainability and performance.
Ans.
- Patterns: (a) plain global functions, (b) constructor with methods inside, (c) constructor with prototype methods, (d) module (revealing module) pattern, and (e) ES6 classes.
- Numerical example (1,000 objects, 10 methods each):
| Pattern | Function objects in memory | Maintainability | Performance |
|---|---|---|---|
| Global functions | 10 | Poor (name clashes, global namespace pollution) | Fast but unsafe |
| Constructor with methods inside | 10 × 1,000 = 10,000 | Good encapsulation | High memory use |
| Constructor with prototype methods (or ES6 class) | 10 (shared) | Good and clear | About 1,000 times fewer function copies, best for many objects |
| Module pattern (closure) | 10 (one instance) | Very good: private state, one namespace | Good for singletons, not for many instances |
- Impact: prototype and module patterns reduce memory and name clashes, and make code easier to test and maintain, while global functions are quick to write but become unmaintainable in large applications. The observer, MVC and MVVM patterns help organise larger code.
MCQs
2026 P-II · Q13. A major advantage of using WebAssembly in computationally intensive web applications is that it:
- (A) Eliminates the need for JavaScript entirely
- (B) Enables near-native execution speed in browsers ✅
- (C) Works only on server-side rendering engines
- (D) None of these
- Answer: (B).
- Why: WebAssembly is a compact binary format, compiled ahead of time from C, C++ or Rust, that the browser runs at close to native speed (games, video editing, simulation). It works alongside JavaScript, not instead of it, and it runs in the browser, not only on servers.