Questions on 7.1 to 7.6
- What is the difference between
letandconst? - What is printed by
console.log('5' + 3)andconsole.log('5' - 3)? - Why prefer
===over==? - When would you choose
switchrather thanif...else? - How do you add an item to the end of an array? How do you loop through it?
- Write an object representing a book and print its title.
- Explain the difference between a function declaration and a function expression.
Show answers
Both are block-scoped. A
letvariable can be reassigned (let age = 20; age = 21;). Aconstvariable cannot be reassigned and must be given a value when it is declared. Note: the *contents* of aconstobject or array can still change (const a = []; a.push(1);is allowed). Useconstby default andletwhen the value must change.console.log('5' + 3)prints **'53'**: with a string,+means concatenation, so 3 becomes'3'.console.log('5' - 3)prints **2**:-only works with numbers, so'5'is converted to the number 5.===(strict equality) compares both value and type with no conversion.==converts types first, which gives surprising results:5 == '5'istrue,0 == ''istrue,null == undefinedistrue. Using===avoids these bugs and makes intent clear.Use
switchwhen one value is compared with many exact options, such as a day number or a menu choice (case 1: … case 2: …). It is easier to read than a long chain ofelse if (x === …). Useif...elsefor ranges and complex conditions such asmarks >= 75.Add to the end with **
push()**:JavaScriptconst fruits = ['mango', 'apple']; fruits.push('banana'); for (let i = 0; i < fruits.length; i++) console.log(fruits[i]); for (const f of fruits) console.log(f); fruits.forEach(f => console.log(f));- JavaScript
const book = { title: 'Learning JavaScript', author: 'S. Perera', year: 2024 }; console.log(book.title); // dot notation console.log(book['title']); // bracket notation A function declaration (
function add(a, b) { return a + b; }) has a name and is hoisted, so it can be called before the line where it is written. A function expression stores a function in a variable (const add = function (a, b) { … };or the arrow formconst add = (a, b) => a + b;); it is not available until that line has run, and calling it earlier causes an error.
Questions on 7.7 to 7.8
- What is the DOM and why is it called a tree?
- Differences between
textContentandinnerHTML? - Which method would you use to select all elements with class
product? - Why is
event.preventDefault()used on form submit? - Why does
setTimeout(show(), 1000)not work as expected? - What is event delegation and why is it useful for dynamically created items?
Show answers
The Document Object Model is the browser's in-memory representation of the HTML page as objects that JavaScript can read and change. It is called a tree because it starts from one root (
document→<html>) and every element has one parent and may have children and siblings, like branches of a tree.textContentgets or sets plain text only; any tags in the value are shown literally. It is faster and safe for user input.innerHTMLgets or sets HTML markup, which the browser parses into elements. Inserting untrusted user input withinnerHTMLcan cause XSS, so use it only with trusted content.
document.querySelectorAll('.product')returns a static NodeList of every element with that class (loop withforEach).document.getElementsByClassName('product')also works and returns a live HTMLCollection.By default, submitting a form sends the data and reloads or navigates the page.
event.preventDefault()stops that, so JavaScript can validate the fields and show error messages (or send the data with AJAX) without the page reloading.show()with brackets calls the function immediately and passes its *return value* (usuallyundefined) tosetTimeout. Pass the function itself instead:setTimeout(show, 1000)orsetTimeout(() => show('Hi'), 1000).Event delegation means adding one listener to a parent element and using
event.targetto find which child was clicked. It works because events bubble up from the child to its parents. It is useful because items created later (for example new list items or products loaded by AJAX) are handled automatically, and fewer listeners are needed.
Questions on 7.9
- Why is client-side validation alone not enough?
- Write a regex for a 5-digit postal code.
Show answers
Client-side validation runs in the user's browser, so it can be bypassed: JavaScript can be turned off, the HTML can be edited in DevTools, or requests can be sent directly with tools such as Postman or curl. It is only for user convenience (quick feedback). The server must always validate again, because it is the only place you control.
- JavaScript
const postal = /^[0-9]{5}$/; // or /^\d{5}$/ postal.test('10115'); // true postal.test('1011a'); // false^and$anchor the start and end so that exactly five digits are accepted.
Questions on 7.10
- What are the three steps repeated in a game loop?
- Explain how a sprite sheet creates animation. What do the 8 arguments of
drawImagemean? - Why store key states in an object instead of moving directly in the
keydownevent? - Write a function that tests if two rectangles overlap.
- What is an anonymous function? Give two places you used one in the game.
Show answers
Update (move objects, check collisions and the score), clear the canvas, and draw everything in its new position.
requestAnimationFrame(loop)then schedules the next frame.A sprite sheet is one image containing many frames of a character in a grid. Showing a different frame every few game ticks creates the illusion of movement, like a flip book.
ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh):img: the sprite sheet;sx, sy, sw, sh: the source rectangle cut from the sheet (sx = frame × frameWidth,sy = row × frameHeight);dx, dy, dw, dh: the destination rectangle where that piece is drawn on the canvas, and its size.
keydownfires once, then repeats only after an operating-system delay, so moving inside the event gives jerky movement and cannot handle two keys at once (for example right and up). Storingkeys[e.key] = true/falseand checking the object in the game loop moves the player smoothly every frame and supports simultaneous keys.- JavaScript
function collides(a, b) { return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y; }This is the AABB test: the rectangles overlap only if they overlap on both the x axis and the y axis.
An anonymous function is a function with no name, written where it is used. In the game: the
keydown/keyupevent listener callbacks, the arrow functions used withforEach/filteron the coins, theimage.onloadhandler, and thesetIntervalcallback. An IIFE is also anonymous.