Schedule > JavaScript Review Quiz (Up to Feb 27)
Answer Key
--------------------------- Part 1 --------------------------- 1. B and D 2. A 3. B 4. A, B, and C 5. C 6. E (All of the above) 7. B 8. B 9. C 10. C 11. B 12. C 13. B 14. C --------------------------- Part 2 --------------------------- 15. 6 16. Bob 17. greet() → "Hello, undefined!" greet('Alice') → "Hello, Alice!" greet('Bob', 'Hi') → "Hi, Bob!" greet('Hi', 'Bob') → "Bob, Hi!" 18. The text “Hello, world!” appears in the <p id="output"> element. --------------------------- Part 3 --------------------------- 19. const multiply = (a, b) => a * b; 20. function addTodo() { const input = document.querySelector('#item-input'); const itemsList = document.querySelector('#items'); const text = input.value; itemsList.insertAdjacentHTML('beforeend', `<li>${text}</li>`); input.value = ''; }
Your Name: ________________________________________
Part A – Multiple Choice
Circle the best answer for each question.
-
Which declaration creates a variable whose value can be changed later? Circle all that apply.
const score = 0;let score = 0;score := 0;var score = 0;const score = 0;
Answer
B and D
letandvarboth create variables that can be reassigned.constcreates a constant that cannot be reassigned after initialization.score := 0;is not valid JavaScript syntax (that’s from other languages like Pascal or Go). Also, even thoughvarallows for reassignment, the recommendation is that modern JavaScript code avoidvarwhen possible. -
What is the result of this code?
let x = 5; let y = "5"; console.log(x == y);truefalseundefined- Throws an error
Answer
A
The
==operator performs loose equality (type coercion). It converts the string"5"to the number5before comparing, so5 == 5evaluates totrue.
-
What is the result of this code?
let x = 5; let y = "5"; console.log(x === y);truefalseundefined- Throws an error
Answer
B
The
===operator performs strict equality (no type coercion). Sincexis a number (5) andyis a string ("5"), they are different types and the comparison evaluates tofalse. -
Which of the following functions all do the same thing?
function add(a, b) { // Option A return a + b; } const add = (a, b) => { // Option B return a + b; } const add = (a, b) => a + b; // Option C function add = (a, b) => a + b; // Option DCircle all that apply:
- Option A
- Option B
- Option C
- Option D
Answer
A, B, and C
- Option A is a function declaration
- Option B is an arrow function with a block body
- Option C is an arrow function with an implicit return (no braces needed for single expression)
- Option D is invalid syntax: you cannot combine
functionkeyword with arrow function syntax
-
What does this code block print to the screen?
function add(a, b) { return a + b; } console.log(add(2, 3));235"2 3"
Answer
C
The function
add(2, 3)adds the two numbers together:2 + 3 = 5. The+operator performs numeric addition when both operands are numbers. -
Given this function definition:
function greet(name, age) { return `Hello, ${name}! You are ${age} years old.`; }Which of the following function calls will work (not throw an error)? Circle all that apply.
greet('Alice')greet('Bob', 25)greet(25, 'Alice')greet('Charlie', 30, 'extra')- All of the above (though not all invocations will work as intended)
- None of the above
Answer
E (All of the above)
JavaScript is flexible with function arguments. Here’s what each call actually outputs:
greet('Alice')→"Hello, Alice! You are undefined years old."(missingageargument)greet('Bob', 25)→"Hello, Bob! You are 25 years old."(correct)greet(25, 'Alice')→"Hello, 25! You are Alice years old."(arguments in wrong order)greet('Charlie', 30, 'extra')→"Hello, Charlie! You are 30 years old."(third argument ignored)
None of these will throw an error, though some won’t produce the intended output.
-
Given:
const user = { name: "Alice", age: 20 };How do you read the user’s name?
user["age"]user.nameuser(name)user->name
Answer
B
In JavaScript, you access object properties using dot notation (
user.name) or bracket notation (user["name"]). The dot notation is more common for simple property names.user["age"]would access the age property, not the name.user(name)would try to calluseras a function, anduser->nameis syntax from other languages like C++ or PHP.
-
Which line correctly selects the first element with class
card?document.getElementById('.card')document.querySelector('.card')document.querySelectorAll('#card')document.querySelector('card')
Answer
B
querySelector('.card')uses CSS selector syntax where.cardselects elements with the classcard.getElementByIdexpects an ID (without the#), not a class selector.querySelectorAllreturns a NodeList of all matching elements, not just the first one.querySelector('card')would look for a<card>element, not a class. -
Given:
<p id="status">Not ready</p>Which line correctly changes the text to
Ready!?document.querySelector('#status').value = 'Ready!';document.querySelector('#status').innerHTML = <p>Ready!</p>;document.querySelector('#status').textContent = 'Ready!';document.querySelector('status').innerText('Ready!');
Answer
C
textContentsets the text content of an element.valueis for form inputs, not paragraph elements.innerHTMLwould kinda work but requires a string with quotes…and it’s bad practice to put a paragraph inside of another paragraph.innerText('Ready!')is incorrect syntax –innerTextis a property, not a method. Also,querySelector('status')should bequerySelector('#status')to select by ID. -
Which
insertAdjacentHTMLcall adds a new<li>as the last item in the list?<ul id="todo-list"></ul>list.insertAdjacentHTML('afterbegin', '<li>Task</li>');list.insertAdjacentHTML('beforebegin', '<li>Task</li>');list.insertAdjacentHTML('beforeend', '<li>Task</li>');list.insertAdjacentHTML('afterend', '<li>Task</li>');
Answer
C
The
insertAdjacentHTMLpositions are:beforebegin- Before the element itselfafterbegin- Inside the element, at the beginningbeforeend- Inside the element, at the end (this is what we want)afterend- After the element itself
-
Why do we often call
event.preventDefault()in a form submit handler?- To stop JavaScript from running on the page
- To prevent the form from submitting and reloading the page
- To clear all form fields automatically
- To disable the submit button
Answer
B
By default, when a form is submitted, the browser sends the form data to the server and reloads the page.
preventDefault()stops this default behavior, allowing JavaScript to handle the form submission without a page reload.
-
Given this HTML:
<button id="toggle-btn">Toggle</button> <div id="box" class="hidden">Content</div>And this JavaScript:
const box = document.getElementById('box'); box.classList.toggle('hidden');What happens when this code runs?
- The
hiddenclass is added to the box - The
hiddenclass is removed from the box - The
hiddenclass is toggled (added if missing, removed if present) - Nothing happens because
classList.toggledoesn’t work on divs
Answer
C
classList.toggle()adds the class if it’s not present, and removes it if it is present. Since the box initially has thehiddenclass,toggle('hidden')will remove it.classList.toggleworks on any element, including divs. - The
-
Given this code:
const heading = document.getElementById('title'); heading.style.color = 'blue';What does this do?
- Adds a CSS class called
colorwith valueblue - Sets the inline style
colorproperty toblue - Changes the text content to “blue”
- Nothing, because
style.coloris not a valid property
Answer
B
The
styleproperty on DOM elements allows you to set inline CSS styles.heading.style.color = 'blue'sets the element’s inlinecolorstyle toblue. This is different from adding a CSS class—it directly modifies the element’s style attribute. - Adds a CSS class called
-
Which method correctly selects an element by its ID?
document.querySelector('#myId')document.getElementById('myId')- Both (a) and (b) are correct
- Neither (a) nor (b) work for IDs
Answer
C
Both methods can select an element by ID:
getElementById('myId')- Specifically designed for IDs (no#needed)querySelector('#myId')- Uses CSS selector syntax (requires#for IDs) Both will return the same element if it exists.
Part B – Short Answer (Code Reading)
-
What does this code log to the console?
let total = 0; for (let i = 1; i <= 3; i++) { total = total + i; } console.log(total);Answer
6The loop runs three times:
- First iteration:
i = 1,total = 0 + 1 = 1 - Second iteration:
i = 2,total = 1 + 2 = 3 - Third iteration:
i = 3,total = 3 + 3 = 6After the loop completes,totalis6.
- First iteration:
-
Given this array of objects, what will be logged to the console?
const students = [ { name: 'Alice', grade: 90 }, { name: 'Bob', grade: 85 }, { name: 'Charlie', grade: 88 } ]; console.log(students[1].name);Answer
'Bob'Array indices start at 0, so:
students[0]is{ name: 'Alice', grade: 90 }students[1]is{ name: 'Bob', grade: 85 }students[2]is{ name: 'Charlie', grade: 88 }Therefore,students[1].nameaccesses thenameproperty of the second object, which is'Bob'.
-
Given this arrow function with default parameters:
const greet = (name, greeting = 'Hello') => { return `${greeting}, ${name}!`; };What will be the output of each function call?
console.log(greet()); console.log(greet('Alice')); console.log(greet('Bob', 'Hi')); console.log(greet('Hi', 'Bob'));Answer
greet()→"Hello, undefined!"-nameisundefined,greetingdefaults to'Hello'greet('Alice')→"Hello, Alice!"-nameis'Alice',greetingdefaults to'Hello'greet('Bob', 'Hi')→"Hi, Bob!"- Both arguments provided correctlygreet('Hi', 'Bob')→"Bob, Hi!"- Arguments are in wrong order:nameis'Hi',greetingis'Bob'
Default parameters only apply when an argument is
undefinedor not provided. The order matters—the first argument always maps toname, the second togreeting. -
Consider the following code:
HTML:
<button id="hello-btn">Say Hello</button> <p id="output"></p>JavaScript:
const button = document.querySelector('#hello-btn'); const output = document.querySelector('#output'); button.addEventListener('click', () => { output.textContent = 'Hello, world!'; });What happens when the user clicks the button?
Answer
The text “Hello, world!” appears in the
<p id="output">element.When the button is clicked:
- The click event fires
- The event listener’s arrow function executes
output.textContent = 'Hello, world!'sets the text content of the paragraph element- The user sees “Hello, world!” displayed on the page
Part C – Short Answer (Code Writing)
-
Rewrite this function declaration as an arrow function:
function multiply(a, b) { return a * b; }Answer
const multiply = (a, b) => a * b;Or with explicit return:
const multiply = (a, b) => { return a * b; };Arrow functions can use implicit return (no braces, no
returnkeyword) when the function body is a single expression. -
You have this HTML:
<input type="text" id="item-input"> <button id="add-btn" onclick="addTodo()">Add</button> <ul id="items"></ul>Write a JavaScript function named
addTodothat:- Reads the text from
#item-inputwhen the button is clicked - Appends a new
<li>with that text to#itemsusinginsertAdjacentHTML - Clears the input after adding
Answer
function addTodo() { const input = document.querySelector('#item-input'); const itemsList = document.querySelector('#items'); const text = input.value; itemsList.insertAdjacentHTML('beforeend', `<li>${text}</li>`); input.value = ''; }Explanation:
querySelector('#item-input')gets the input element by IDquerySelector('#items')gets the<ul>element by IDinput.valuereads the text from the inputinsertAdjacentHTML('beforeend', ...)adds the new<li>at the end of the listinput.value = ''clears the input field after adding the item
- Reads the text from