JavaScript

JavaScript adds behavior to web pages: it reads and changes the DOM, responds to user input, performs calculations, and connects to servers. Good JavaScript is readable, predictable, and small — prefer named functions, clear variable names, and explicit conversions when working with user input. This chapter covers core ideas (printing output, DOM selection, events, small reusable functions) with copyable examples and finishes with a working calculator for subtraction (final example shown as a single index.html file with inline <script defer> in the head).
Hello World
The simplest test is logging to the console while you learn.
console.log("Hello, world!");
Selecting the DOM
Use document.querySelector for single elements and querySelectorAll for lists. Change text with textContent and attributes with setAttribute. Keep selectors simple and cache repeated queries in variables.
const title = document.querySelector("h1");
title.textContent = "Updated by JavaScript";
Events & handlers
Attach behavior with addEventListener. Keep handlers thin: validate input, call a named function, and update the UI. Avoid inline handlers in HTML when possible for clarity and testability.
const btn = document.querySelector("#calc");
btn.addEventListener("click", calculate);
function calculate(){ console.log("clicked"); }
Small reusable function
Write functions that accept inputs and return results. Convert user input to numbers explicitly using Number() to avoid string concatenation when performing arithmetic.
function add(a, b){ return Number(a) + Number(b); }
console.log(add("2", 3)); // 5
Final example — calculator for subtraction
The final example below is a single index.html file with inline <script defer> in the head. It shows two inputs, a button, and a result area. Save as index.html and open in a browser to test.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Subtract Calculator</title>
<script defer>
function calculateDifference(){
const minuend = Number(document.querySelector("#minuend").value);
const subtrahend = Number(document.querySelector("#subtrahend").value);
const difference = minuend - subtrahend;
document.querySelector("#result").textContent = "Difference: " + difference;
}
</script>
</head>
<body>
<h1>Subtract Calculator</h1>
<label>Minuend: <input id="minuend" type="number" /></label><br />
<label>Subtrahend: <input id="subtrahend" type="number" /></label><br />
<button id="calc" type="button" onclick="calculateDifference()">Calculate</button><br />
<div id="result">Difference: </div>
</body>
</html>
MCQs
1. Which method writes a message to the browser console for debugging?
(a) print()
(b) console.log()
(c) document.alert()
(d) window.show()
► (b) console.log()
2. Which selector returns the first <h1> element in the document?
(a) document.getElementsByTagName("h1")[0]
(b) document.querySelector("h1")
(c) document.querySelectorAll("h1")[0]
(d) All of the above
► (d) All of the above
3. What does Number("3.5") return?
(a) "3.5"
(b) 3.5
(c) NaN
(d) 35
► (b) 3.5
4. Which is the correct way to attach a click listener without overwriting others?
(a) element.onclick = handler
(b) element.addEventListener("click", handler)
(c) element.attachEvent("click", handler)
(d) element.on("click", handler)
► (b) element.addEventListener("click", handler)
5. Which declaration creates a block-scoped, reassignable variable?
(a) var
(b) let
(c) const
(d) static
► (b) let
6. What is the type returned by typeof NaN?
(a) "NaN"
(b) "number"
(c) "undefined"
(d) "object"
► (b) "number"
7. Which operator checks both value and type equality?
(a) ==
(b) !=
(c) ===
(d) =
► (c) ===
8. What does element.textContent do?
(a) Returns and sets HTML markup inside the element
(b) Returns and sets only the text content (no HTML parsing)
(c) Returns computed style text
(d) Deletes the element
► (b) Returns and sets only the text content (no HTML parsing)
9. Which of these converts the string "08" reliably to number 8?
(a) parseInt("08")
(b) parseInt("08", 10)
(c) Number("08")
(d) Both (b) and (c)
► (d) Both (b) and (c)
10. Which method stops a form submission so JavaScript can handle it?
(a) event.stopPropagation()
(b) event.preventDefault()
(c) return false
(d) event.cancel()
► (b) event.preventDefault()
11. Which value is considered falsy in JavaScript?
(a) 0
(b) "" (empty string)
(c) null
(d) All of the above
► (d) All of the above
12. How do you check if an object is an array?
(a) typeof arr === "array"
(b) Array.isArray(arr)
(c) arr instanceof Array === false
(d) arr.length === undefined
► (b) Array.isArray(arr)
13. Which syntax defines an arrow function that returns the sum of two numbers?
(a) function sum(a,b) { return a + b; }
(b) const sum = (a, b) => a + b;
(c) let sum = a, b => a + b;
(d) def sum(a,b): return a + b
► (b) const sum = (a, b) => a + b;
14. Which selection will return all <p> elements?
(a) document.querySelector("p")
(b) document.getElementById("p")
(c) document.querySelectorAll("p")
(d) document.getElementsByClassName("p")
► (c) document.querySelectorAll("p")
15. If a variable is assigned without let/const/var in non-strict mode, what happens?
(a) It becomes a global variable
(b) It throws an error
(c) It is block-scoped
(d) It is garbage collected immediately
► (a) It becomes a global variable
16. Which console method logs an error-level message?
(a) console.log()
(b) console.info()
(c) console.error()
(d) console.warn()
► (c) console.error()
17. Which practice keeps event handlers small and easy to test?
(a) Put all logic inside anonymous handlers
(b) Call small named functions from handlers
(c) Use inline onclick attributes
(d) Avoid functions altogether
► (b) Call small named functions from handlers
18. What will parseInt("08") return in modern engines without a radix?
(a) 0
(b) 8
(c) NaN
(d) 80
► (b) 8