Unit 7 · JavaScript

7.11Review Questions

On this page
  1. Questions on 7.1 to 7.6
  2. Questions on 7.7 to 7.8
  3. Questions on 7.9
  4. Questions on 7.10

Questions on 7.1 to 7.6

  1. What is the difference between let and const?
  2. What is printed by console.log('5' + 3) and console.log('5' - 3)?
  3. Why prefer === over ==?
  4. When would you choose switch rather than if...else?
  5. How do you add an item to the end of an array? How do you loop through it?
  6. Write an object representing a book and print its title.
  7. Explain the difference between a function declaration and a function expression.
Show answers
  1. Both are block-scoped. A let variable can be reassigned (let age = 20; age = 21;). A const variable cannot be reassigned and must be given a value when it is declared. Note: the *contents* of a const object or array can still change (const a = []; a.push(1); is allowed). Use const by default and let when the value must change.

  2. 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.

  3. === (strict equality) compares both value and type with no conversion. == converts types first, which gives surprising results: 5 == '5' is true, 0 == '' is true, null == undefined is true. Using === avoids these bugs and makes intent clear.

  4. Use switch when 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 of else if (x === …). Use if...else for ranges and complex conditions such as marks >= 75.

  5. Add to the end with **push()**:

    JavaScript
    const 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));
  6. JavaScript
    const book = {
      title: 'Learning JavaScript',
      author: 'S. Perera',
      year: 2024
    };
    console.log(book.title);      // dot notation
    console.log(book['title']);   // bracket notation
  7. 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 form const 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

  1. What is the DOM and why is it called a tree?
  2. Differences between textContent and innerHTML?
  3. Which method would you use to select all elements with class product?
  4. Why is event.preventDefault() used on form submit?
  5. Why does setTimeout(show(), 1000) not work as expected?
  6. What is event delegation and why is it useful for dynamically created items?
Show answers
  1. 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.

    • textContent gets or sets plain text only; any tags in the value are shown literally. It is faster and safe for user input.
    • innerHTML gets or sets HTML markup, which the browser parses into elements. Inserting untrusted user input with innerHTML can cause XSS, so use it only with trusted content.
  2. document.querySelectorAll('.product') returns a static NodeList of every element with that class (loop with forEach). document.getElementsByClassName('product') also works and returns a live HTMLCollection.

  3. 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.

  4. show() with brackets calls the function immediately and passes its *return value* (usually undefined) to setTimeout. Pass the function itself instead: setTimeout(show, 1000) or setTimeout(() => show('Hi'), 1000).

  5. Event delegation means adding one listener to a parent element and using event.target to 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

  1. Why is client-side validation alone not enough?
  2. Write a regex for a 5-digit postal code.
Show answers
  1. 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.

  2. 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

  1. What are the three steps repeated in a game loop?
  2. Explain how a sprite sheet creates animation. What do the 8 arguments of drawImage mean?
  3. Why store key states in an object instead of moving directly in the keydown event?
  4. Write a function that tests if two rectangles overlap.
  5. What is an anonymous function? Give two places you used one in the game.
Show answers
  1. 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.

  2. 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.
  3. keydown fires 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). Storing keys[e.key] = true/false and checking the object in the game loop moves the player smoothly every frame and supports simultaneous keys.

  4. 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.

  5. An anonymous function is a function with no name, written where it is used. In the game: the keydown/keyup event listener callbacks, the arrow functions used with forEach/filter on the coins, the image.onload handler, and the setInterval callback. An IIFE is also anonymous.