JavaScript is the scripting language every browser runs: it validates forms, reacts to events and rewrites the page through the DOM. Its loose typing (typeof, == coercion, truthy/falsy), scoping (var/let/const, hoisting, closures) and event model are classic output-prediction material.
High-yield 75 minSyllabus: “Client side scripting: JavaScript”
Mark as
The idea in one minute
HTML is the stage set and CSS the lighting; JavaScript is the stage crew working during the show. It waits for cues — a click, a key press, a reply from the server — and then moves props, changes signs and hands notes to the actors without stopping the play. The crew's script book is the DOM: a live map of every object on stage that the crew can find by name and change.
Key points — the night-before list
Created by Brendan Eich at Netscape in 1995; standardised as ECMAScript (ECMA-262). ES2015 (ES6) brought let/const, arrow functions, classes, modules, promises.
Eight types: number, string, boolean, undefined, null, symbol, bigint (primitives) and object. typeof null is "object"; typeof function(){} is "function".
var is function-scoped and hoisted as undefined; let/const are block-scoped and in the temporal dead zone (ReferenceError) until declared; const cannot be reassigned.
== converts types first ("5" == 5 is true); === also compares type ("5" === 5 is false). With a string + concatenates: "3" + 2 * "4" gives "38".
Falsy: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy — including "0", "false", [] and {}.
Events: addEventListener allows many handlers; capture phase → target → bubble phase; preventDefault() stops the default action, stopPropagation() stops propagation.
BOM: window, alert/confirm/prompt, location, history, navigator, screen; setTimeout/setInterval callbacks run only after the current code finishes.
01What JavaScript is and where scripts go
JavaScript was written by Brendan Eich at Netscape in about ten days in May 1995 (as Mocha, then LiveScript) and shipped in Netscape Navigator 2.0. Despite the name it is unrelated to Java. Ecma International standardises it as ECMAScript (ECMA-262): ES1 in 1997, ES3 in 1999, ES5 in 2009, the major ES2015 (ES6) release, and a new edition every year since.
It is a high-level, dynamically typed, interpreted (in practice just-in-time compiled) language with first-class functions and prototype-based objects. A browser runs it in an engine — V8 (Chrome, Edge), SpiderMonkey (Firefox), JavaScriptCore (Safari) — on a single main thread driven by an event loop. Node.js (2009) runs the same language on servers. Client-side scripting means code downloaded with the page and executed by the browser: validating forms before submission, reacting to clicks, updating parts of the page, talking to the server with AJAX.
HTML
<head><script src="lib.js" defer></script><!-- downloads in parallel, runs after parsing, in order --><script src="stats.js" async></script><!-- runs as soon as it arrives; order not guaranteed --></head><body><p id="msg">Loading…</p><script>
// an inline script at the end of body can already see the elements above it
document.getElementById("msg").textContent = "Ready";
</script><noscript>Please enable JavaScript to use the allotment portal.</noscript></body>
A plain <script> in the head blocks HTML parsing while it downloads and runs, and cannot yet see elements of the body. Put such scripts at the end of the body, or use defer.
src names an external file (never href); the file is cached and shared by many pages. type="module" loads an ES module, which is deferred automatically.
defer: download during parsing, execute after the document is parsed, in document order. async: execute the moment the file arrives — good for independent scripts such as analytics.
noscript holds content shown only when scripting is disabled or unsupported.
Ways to output: console.log() (developer console), alert() (dialog), document.write() (writes into the page while it loads — calling it after load wipes the page), and changing the DOM with textContent / innerHTML.
Tip
Every snippet in this topic can be pasted into the Web playground tool on this page; open the console panel to see console.log output.
02Values, types and typeof
JavaScript has eight data types. Seven are primitives (immutable values): number (one 64-bit IEEE 754 floating-point type for integers and decimals, including NaN and Infinity), string, boolean, undefined (a variable declared but not assigned), null (deliberately 'no value'), symbol (unique identifiers, ES6) and bigint (arbitrary-size integers such as 10n, ES2020). Everything else — plain objects, arrays, functions, dates, regular expressions — is an object.
JavaScript
typeof 42 // "number" (also 3.14, NaN, Infinity)
typeof "KSHB" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" <- a 1995 bug kept for compatibility
typeof { units: 120 } // "object"
typeof [1, 2] // "object" <- use Array.isArray([1, 2]) -> true
typeof function () {} // "function" (functions are objects, but typeof says "function")
typeof Symbol("id") // "symbol"
typeof 10n // "bigint"
typeof new Number(5) // "object" (a wrapper object, not a primitive)
0.1 + 0.2 // 0.30000000000000004 (binary floating point)
5 / 0 // Infinity
"abc" * 2 // NaN — and typeof NaN is "number"
Because variables are dynamically typed, the same variable can hold a number now and a string later; the value has a type, the variable does not. Wrapper objects created with new Number(), new String() or new Boolean() are objects, so 5678 === new Number(5678) is false, and new Boolean(false) is truthy — every object is.
PSC favourite
Output questions love these: var s; alert(s) shows undefined; typeof null is "object"; var x = new Boolean("false") makes x a Boolean object wrapping true (a non-empty string converts to true).
Hoisting means declarations are processed before any code in their scope runs. A var is created and set to undefined at the top of its function, so reading it early gives undefined. let and const are also registered early but stay uninitialised; the stretch from the start of the block to the declaration is the temporal dead zone (TDZ), and touching the variable there throws a ReferenceError. Function declarations are hoisted completely — you can call them above the line where they are written — but a function expression stored in a var is undefined until that line runs.
JavaScript
console.log(total); // undefined — var is hoisted
var total = 5;
console.log(area(4)); // 16 — function declarations are hoisted with their body
function area(side) { return side * side; }
{
var a = 1; // var ignores the block
let b = 2; // let lives only inside it
}
console.log(a); // 1
console.log(typeof b); // "undefined" — b does not exist out here
const rate = 0.05;
// rate = 0.06; // TypeError: assignment to a constant variable
const scheme = { units: 120 };
scheme.units = 140; // allowed: the binding is constant, the object is not
Assigning to a name that was never declared (count = 1;) silently creates a global variable in sloppy mode; "use strict"; at the top of a script or function turns that into an error, along with other unsafe actions. ES modules and classes are always strict.
04Operators, == vs === and truthy/falsy
The loose equality operator == converts its operands to a common type before comparing; the strict equality (identity) operator === returns true only when both type and value match, with no conversion. != and !== are their negations. Prefer === everywhere.
Expression
Result
Why
"10" == 10
true
the string is converted to a number
"10" === 10
false
different types
2 == 2.0, 2 === 2.0
true, true
there is only one number type
0 == "", 0 == "0", "" == "0"
true, true, false
== is not transitive
null == undefined
true
special rule: they equal each other and nothing else
null === undefined
false
different types
null == 0, null >= 0
false, true
relational operators convert null to 0; == does not
NaN == NaN
false
NaN equals nothing — test with Number.isNaN()
"5" + 2
"52"
+ with a string concatenates
"5" - 2, "5" * "2"
3, 10
-, * and / always convert to numbers
"3" + 2 * "4"
"38"
multiplication first (8), then string + number
true + 1, null + 1, undefined + 1
2, 1, NaN
true → 1, null → 0, undefined → NaN
[] + [], [1, 2] + [3]
"", "1,23"
arrays convert to comma-joined strings
In a condition every value is treated as true or false. Exactly eight values are falsy: false, 0, -0, 0n, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", "false", [], {} and every object.
JavaScriptLogical operators return one of their operands, not necessarily a boolean
const name = "" || "guest"; // "guest" — || returns the first truthy operand
const count = 0 ?? 5; // 0 — ?? replaces only null or undefined
const ok = "a" && "b"; // "b" — && returns the first falsy operand, else the last
const user = { name: "Anil", address: null };
console.log(user.address?.city); // undefined instead of a TypeError (optional chaining)
let x = 7;
x += 3; x **= 2; x %= 7; // assignment operators: x is 10, then 100, then 2
let cfg = null;
cfg ??= { theme: "light" }; // logical assignment (ES2021): set only if null/undefined
console.log(typeof x, x > 1 ? "big" : "small", "units" in { units: 1 });
PSC favourite
Valid JavaScript operators include &=, !==, === and ??= — all four (asked in 2023). Also remember the comma operator: in x[0, 1, 2] the expression 0, 1, 2 evaluates to its last value, so it means x[2].
05Functions, arrow functions and closures
JavaScript
// 1. declaration — hoisted
function fee(amount, rate = 0.05, ...extras) { // default and rest parameters
return amount * rate + extras.reduce((sum, e) => sum + e, 0);
}
fee(1000); // 50
fee(1000, 0.1); // 100
fee(1000, undefined, 20, 30); // 100 — undefined triggers the default, extras = [20, 30]// 2. expression — not hoisted
const discount = function (price) { return price * 0.9; };
// 3. arrow function (ES6) — short syntax, no own this or arguments, cannot be used with new
const square = (n) => n * n;
const add = (a, b) => { const s = a + b; return s; };
// functions are values: pass them to other functions (callbacks)
[3, 1, 2].sort((p, q) => p - q); // [1, 2, 3]
A closure is a function bundled with the variables of the scope where it was created. Even after the outer function has returned, the inner function keeps access to those variables — they stay alive as long as the inner function does. Closures give private state without classes and are how callbacks remember their context.
JavaScript
function makeCounter(start = 0) {
let count = start; // private: no code outside can touch it
return {
inc: () => ++count,
reset: () => (count = start),
};
}
const c1 = makeCounter();
const c2 = makeCounter(10);
console.log(c1.inc(), c1.inc(), c2.inc(), c1.inc(), c1.reset(), c1.inc());
// 1 2 11 3 0 1 — each counter has its own count
this depends on how a normal function is called: inside obj.method() it is obj; in a plain call it is undefined (strict mode) or the global object; in an event handler registered with addEventListener it is the element. Arrow functions have no this of their own and use the this of the surrounding code — handy inside callbacks, wrong as object methods that need this.
Add at the end (returns new length) / remove the last (returns it)
Yes
unshift(x) / shift()
Add at the front / remove the first (returns it)
Yes
splice(i, n, …items)
Remove n items at index i and insert items; returns the removed ones
Yes
slice(i, j)
Copy from index i up to, but not including, j
No
concat, join(", ")
Combine arrays / build a string
No
indexOf(x), includes(x), find(fn)
Position (−1 if absent) / membership / first match
No
map(fn)
New array of fn's results, same length
No
filter(fn)
New array of the elements for which fn is truthy
No
reduce(fn, init)
Fold all elements into one value (sum, max, object)
No
forEach(fn)
Run fn for each element; returns undefined
No
sort(), reverse()
Sort (as strings unless given a compare function) / reverse
Yes
JavaScript
const units = [120, 64, 48, 200];
units.map(u => u / 4); // [30, 16, 12, 50]
units.filter(u => u > 60); // [120, 64, 200]
units.reduce((sum, u) => sum + u, 0); // 432
[10, 9, 1].sort(); // [1, 10, 9] — compared as strings!
[10, 9, 1].sort((a, b) => a - b); // [1, 9, 10]
const s = "Kerala State Housing Board";
s.length; // 26
s.indexOf("State"); // 7 (0-based; -1 if absent)
s.slice(7, 12); // "State"
s.toUpperCase(); // "KERALA STATE HOUSING BOARD"
s.split(" "); // ["Kerala", "State", "Housing", "Board"]
s.replace("Board", "Portal"); // "Kerala State Housing Portal"
" x ".trim(); // "x"
const who = "Anil";
const msg = `Welcome, ${who}!`; // template literal (ES6): "Welcome, Anil!"
JSON is the text format for exchanging data with servers. JSON.stringify(value) turns an object into a JSON string; JSON.parse(text) turns JSON text back into objects. JSON is stricter than JavaScript object syntax: keys and strings need double quotes, there are no comments, trailing commas, functions or undefined — stringify silently drops function and undefined properties.
When a browser loads a page it builds the Document Object Model (DOM): a tree of node objects — the document at the root, then elements, attributes and text — exposed to JavaScript. Through the DOM a script can find, change, add and delete any HTML element, change any attribute or CSS style, and react to events. The DOM is a W3C/WHATWG standard; it is a tree, not a linked list of objects.
JavaScript
const list = document.querySelector("#schemeList"); // first match of a CSS selector
const items = document.querySelectorAll("#schemeList li"); // static NodeList of all matches
const one = document.getElementById("note"); // by id (fastest)
const all = document.getElementsByClassName("scheme"); // live HTMLCollection
const li = document.createElement("li"); // build a new element
li.textContent = "Thanal Homes (48 units)"; // treated as plain text: safe
li.setAttribute("data-id", "s3");
li.classList.add("new");
li.style.color = "green"; // inline style; CSS names become camelCase
list.appendChild(li); // attach it to the page
one.innerHTML = "<b>3</b> schemes open"; // parses the string as HTML
items[0].remove(); // delete a node
textContent
Gets or sets plain text; markup is shown literally
Safe for user input — nothing is parsed
Fast; ignores CSS
innerHTML
Gets or sets HTML markup, which the browser parses
Dangerous with user input — enables cross-site scripting (XSS)
Replaces all child nodes and their event handlers
An event is a signal that something happened: click, dblclick, mouseover, keydown, input, change, submit, focus, blur, load, DOMContentLoaded. Handlers can be attached three ways: an HTML attribute (<button onclick="save()">, old and mixes code with markup), a DOM property (btn.onclick = save; — only one handler per event), or btn.addEventListener("click", save) — any number of handlers, removable with removeEventListener, and with control over the phase.
How an event travels (event flow)
Capturing phase
The event travels down from window and document through each ancestor to the target. Listeners registered with addEventListener(type, fn, true) run on the way down.
Target phase
Listeners on the element that was actually clicked run. event.target is this element.
Bubbling phase
The event travels back up through the ancestors to window; ordinary listeners (the default) run here. event.currentTarget is the element whose listener is running.
Default action
Afterwards the browser does its normal job — follows the link, submits the form, types the character — unless a handler called event.preventDefault().
event.stopPropagation() stops the event from reaching further elements (it does not cancel the default action); event.preventDefault() cancels the default action (it does not stop propagation). Bubbling enables event delegation: one listener on a parent list handles clicks on every current and future child, using event.target to see which one.
JavaScriptThe form has fields named username and password and an empty element with id errors
// client-side validation of the login form (the server must still re-check!)
const form = document.getElementById("loginForm");
form.addEventListener("submit", function (event) {
const user = form.username.value.trim();
const pass = form.password.value;
const problems = [];
if (user.length < 3) problems.push("Username needs at least 3 characters.");
if (!/^(?=.*\d).{8,}$/.test(pass)) problems.push("Password needs 8+ characters including a digit.");
if (problems.length > 0) {
event.preventDefault(); // do not send the form
document.getElementById("errors").textContent = problems.join(" ");
}
});
08BOM, timers, regular expressions, errors and ES6+
The Browser Object Model (BOM) is everything the browser exposes besides the document. window is the global object (global var variables and functions become its properties); its children include document, location, history, navigator and screen.
JavaScriptThe three dialog boxes are alert(), confirm() and prompt(); msgbox() belongs to VBScript
alert("Saved"); // message only
const go = confirm("Submit your application?"); // OK -> true, Cancel -> false
const name = prompt("Your name?", ""); // the typed string, or null if cancelled
location.href; // full URL; also location.hostname, .pathname, .search, .hash// location.href = "status.html"; navigate; location.reload() reloads; location.replace() skips history// history.back(); history.forward(); history.go(-2);
navigator.userAgent; // browser identification; also navigator.language, navigator.onLine
screen.width; // screen size; window.innerWidth is the viewport
const id = setInterval(() => console.log("tick"), 1000); // repeat every second
setTimeout(() => clearInterval(id), 3500); // stop after three ticks
setTimeout(fn, ms) runs fn once after at least ms milliseconds; setInterval(fn, ms) repeats it; both return an id for clearTimeout / clearInterval. Because JavaScript is single-threaded, a timer callback runs only when the call stack is empty — even setTimeout(fn, 0) waits until the current script finishes, and promise callbacks (microtasks) run before timer callbacks.
JavaScript
const pin = /^[1-9][0-9]{5}$/; // Indian PIN code: 6 digits, not starting with 0
pin.test("691001"); // true
pin.test("091001"); // false
const mobile = /^[6-9]\d{9}$/; // 10 digits starting 6-9
"Call 9447012345 or 0471-2345678".match(/\d{10}/g); // ["9447012345"]
"KSHB-kshb".replace(/kshb/gi, "Board"); // "Board-Board" (g = global, i = ignore case)
function parseUnits(text) {
const n = Number(text);
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("Units must be a non-negative integer: " + text);
}
return n;
}
try {
parseUnits("-5");
} catch (e) {
console.log(e.name + ": " + e.message); // RangeError: Units must be a non-negative integer: -5
} finally {
console.log("validation finished"); // always runs
}
Regular-expression basics: ^ and $ anchor the start and end; \d is a digit, \w a word character, \s whitespace, . any character; [abc] a set and [^abc] its complement; quantifiers + (one or more), ? (optional), {n}, {n,m} and the star for zero or more; flags g, i, m. Built-in error types: Error, SyntaxError, ReferenceError (unknown variable), TypeError (wrong type, e.g. calling a non-function), RangeError (value outside the allowed range), URIError, EvalError.
Try the problem first, then reveal the working one step at a time.
EX 1Predicting output: hoisting and scope
What does this print, line by line? console.log(a); var a = 5; · console.log(sq(4)); function sq(n) { return n * n; } · try { console.log(b); } catch (e) { console.log(e.name); } let b = 10; · { var c = 1; let d = 2; } console.log(c); console.log(typeof d); · try { cube(2); } catch (e) { console.log(e.name); } var cube = function (n) { return n * n * n; };
EX 2Evaluating coercion expressions
Give the value of: (a) "5" + 2 (b) "5" - 2 (c) "3" + 2 * "4" (d) true + 1 (e) [1, 2] + [3] (f) 0 == "" (g) null >= 0 (h) NaN === NaN (i) 5678 === new Number(5678)
EX 3Event capturing and bubbling order
A page has <div id="outer"><button id="btn">Apply</button></div>. Listeners: on document, bubbling, logs "document"; on outer, capturing (third argument true), logs "outer-capture"; on outer, bubbling, logs "outer-bubble"; on btn, logs "button" + event.target.id. The user clicks the button. What is logged? What changes if the button's handler calls event.stopPropagation()?
EX 4The event loop, timers and closures in loops
Predict the output: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); followed by for (var i = 0; i < 3; i++) setTimeout(() => console.log("var", i), 0); and for (let j = 0; j < 3; j++) setTimeout(() => console.log("let", j), 0);
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Predict each line: const units = [120, 64, 48, 200]; then (1) units.map(u => u / 4) (2) units.filter(u => u > 60) (3) units.reduce((s, u) => s + u, 0) (4) units.slice(1, 3) (5) units.splice(1, 2, 99) and then units (6) [1, 2, 3].forEach(x => x * 2)
Q2
Write a function makeLimiter(max) that returns a function; each call returns true while it has been called at most max times in total, and false afterwards. Show the output of calling const allow = makeLimiter(2); four times.
Q3
Give typeof for each: 42, "42", true, undefined, null, {}, [], function(){}, NaN, 10n, Symbol("x"), new Number(5). Which two results surprise beginners most, and how do you test for an array?
Q4
Write a regular expression for a 6-digit Indian PIN code that does not start with 0, and say whether each matches: "691001", "091001", "69100", "6910011". Why are ^ and $ essential?
Q5
Write JavaScript that adds a new list item 'Harbour View (60 units)' to the list with id schemes, makes clicking any item in that list (now or later) toggle a CSS class done on it using a single listener, and explain why you used textContent rather than innerHTML.
Exam traps
typeof null is "object", typeof [] is "object", and typeof NaN is "number" — use === null, Array.isArray() and Number.isNaN().
[10, 9, 1].sort() gives [1, 10, 9]: without a compare function elements are compared as strings.
preventDefault() cancels the browser's default action; stopPropagation() stops the event reaching other elements — they are not the same.
const stops reassignment of the variable, not changes inside the object or array it refers to.
setTimeout(fn, 0) does not run immediately: it waits until the current script (and pending promise callbacks) finish.
2 == 2.0 and 2 === 2.0 are both true — JavaScript has only one number type, so there is no type difference to catch.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
JavaScript & the DOM · Question 1 of 12✓ 0 · ✗ 0
What does typeof null return in JavaScript?
Past-paper questions on this topic
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
Past papers · Question 1 of 30✓ 0 · ✗ 0
Modelled on QP 105/2024 · Higher Secondary School Teacher (Junior) Computer Science (8 Aug 2024), Q.85 (reworded)original paper (PDF)
Spelled exactly as it must appear in code, which JavaScript keyword declares a constant?