Midterm Evaluation Preview

JavaScript Practice Guide

This preview includes:

  • 40 multiple-choice questions with answers
  • 10 code blocks to explain
  • A mix of playful and practical scenarios

Part A — Multiple Choice Questions

Question 1

A wizard tries to store a dragon name that will never change.

const dragon = 'Fluffy'
dragon = 'Steve'

What happens?

A. The value changes to 'Steve'
B. JavaScript ignores the second line
C. An error occurs because const cannot be reassigned
D. The variable becomes an array

Answer: C

Why: Variables declared with const cannot be reassigned after their first value is set. The second line tries to replace 'Fluffy' with 'Steve', so JavaScript throws an error.


Question 2

Which variable declaration is best for a shopping cart array that will have items added to it?

const cart = []
cart.push('Laptop')

A. const, because the array can be mutated
B. let, because arrays always require let
C. var, because push() only works with var
D. No variable is needed

Answer: A

Why: const prevents reassignment of the variable, but it does not prevent changes inside an array or object. You can still use methods like push() to modify the array.


Question 3

A raccoon developer writes:

const snacks = ['chips', 'cookies', 'pizza']
console.log(snacks[1])

What is printed?

A. chips
B. cookies
C. pizza
D. undefined

Answer: B

Why: Array indexes start at 0. snacks[0] is 'chips', snacks[1] is 'cookies', and snacks[2] is 'pizza'.


Question 4

Given the array:

const prices = [19.99, 5.99, 12.49]

Which code correctly adds 8.99 to the end?

A. prices.add(8.99)
B. prices.push(8.99)
C. prices.end(8.99)
D. prices.insert(8.99)

Answer: B

Why: The push() method adds one or more items to the end of an array.


Question 5

A pirate wants the last treasure from this array:

const treasures = ['gold', 'map', 'rubber duck']

Which code retrieves 'rubber duck'?

A. treasures[3]
B. treasures[2]
C. treasures.last()
D. treasures[-1]

Answer: B

Why: The array has three items, but the indexes are 0, 1, and 2. The last item is at index 2.


Question 6

What does querySelector() return?

A. All matching elements
B. The first matching element
C. Only elements with an ID
D. A string containing HTML

Answer: B

Why: querySelector() returns the first element that matches the CSS selector. To get all matching elements, use querySelectorAll().


Question 7

A zombie wants to select the element with this HTML:

<h1 id="brain">Brains</h1>

Which JavaScript is correct?

A. document.getElementById('#brain')
B. document.getElementById('brain')
C. document.querySelector('brain')
D. document.selectId('brain')

Answer: B

Why: getElementById() only needs the ID name without the #. The # is used with CSS selectors, such as in querySelector('#brain').


Question 8

Which property should be used to change only the text inside an element?

A. textContent
B. innerHTML
C. classList
D. styleText

Answer: A

Why: textContent changes the text inside an element. innerHTML is used when inserting or replacing HTML markup.


Question 9

A cat writes:

const name = 'Mr. Whiskers'
const sentence = `Hello, ${name}!`

What is the value of sentence?

A. Hello, name!
B. Hello, ${name}!
C. Hello, Mr. Whiskers!
D. Hello, undefined!

Answer: C

Why: Template literals use backticks and ${} placeholders to insert variable values into a string.


Question 10

Which option correctly creates an object?

A.

const student = ['name': 'Ana']

B.

const student = {
  name: 'Ana',
  grade: 92
}

C.

const student = (
  name = 'Ana'
)

D.

const student = 'name', 'Ana'

Answer: B

Why: Object literals use curly braces {} and store data as key-value pairs, such as name: 'Ana'.


Question 11

A goose has this object:

const goose = {
  name: 'Gary',
  mood: 'chaotic'
}

How do you access the mood?

A. goose[mood]
B. goose.mood
C. goose->mood
D. goose/mood

Answer: B

Why: Dot notation uses the object name followed by the property name: goose.mood.


Question 12

Given:

const user = {
  firstName: 'Maya',
  lastName: 'Chen'
}

Which code updates the last name?

A. user.lastName = 'Singh'
B. user(lastName) = 'Singh'
C. user.update('lastName', 'Singh')
D. lastName.user = 'Singh'

Answer: A

Why: Existing object properties can be updated using dot notation and the assignment operator.


Question 13

A vampire writes:

const vampire = {
  name: 'Count Debugula'
}

vampire.age = 400

What happens?

A. Error, because const objects cannot change
B. The age property is added
C. The object becomes an array
D. JavaScript deletes the object

Answer: B

Why: A const object cannot be reassigned to a new object, but its properties can be added, removed, or updated.


Question 14

What does Object.keys(product) return?

const product = {
  title: 'Notebook',
  price: 4.99
}

A. ['Notebook', 4.99]
B. [['title', 'Notebook'], ['price', 4.99]]
C. ['title', 'price']
D. 'title price'

Answer: C

Why: Object.keys() returns an array containing only the property names of the object.


Question 15

A robot chef has:

const recipe = {
  name: 'Laser Soup',
  difficulty: 'dangerous'
}

What does Object.values(recipe) return?

A. ['name', 'difficulty']
B. ['Laser Soup', 'dangerous']
C. { Laser Soup, dangerous }
D. recipe.values

Answer: B

Why: Object.values() returns an array containing only the values from the object.


Question 16

What does Object.entries() return?

A. Only the keys of an object
B. Only the values of an object
C. An array of key-value pairs
D. A string version of the object

Answer: C

Why: Object.entries() returns an array where each item is another array containing a key and its value.


Question 17

A dinosaur loops through snacks:

const snacks = ['taco', 'burger', 'cookie']

for (const snack of snacks) {
  console.log(snack)
}

How many times does the loop run?

A. 1
B. 2
C. 3
D. 4

Answer: C

Why: The array has three items, so the for...of loop runs once for each item.


Question 18

Which loop is best when you want to loop directly through the values of an array?

A. for...of
B. for...in
C. switch
D. if...else

Answer: A

Why: for...of is designed to loop through the values of iterable objects, such as arrays.


Question 19

A clown writes:

const jokes = ['pie', 'banana', 'squeaky shoe']
const result = jokes.push('rubber chicken')

What is stored in result?

A. The updated array
B. The new length of the array
C. The added item
D. undefined

Answer: B

Why: push() adds the item to the array and returns the new length of the array.


Question 20

What does .pop() do?

A. Removes the first item
B. Removes the last item
C. Adds an item to the end
D. Sorts the array

Answer: B

Why: The pop() method removes the last item from an array and returns that removed item.


Question 21

A student writes:

const goblins = ['Greg', 'Gina', 'Gus']
goblins.shift()

What is now inside goblins?

A. ['Greg', 'Gina']
B. ['Gina', 'Gus']
C. ['Greg', 'Gus']
D. []

Answer: B

Why: shift() removes the first item from an array. 'Greg' is removed, so only 'Gina' and 'Gus' remain.


Question 22

Which method adds an item to the beginning of an array?

A. push()
B. pop()
C. shift()
D. unshift()

Answer: D

Why: unshift() adds one or more items to the beginning of an array.


Question 23

A banana programmer writes:

const nums = [10, 2, 30]
nums.sort()

What is the likely result?

A. [2, 10, 30]
B. [10, 2, 30]
C. [10, 2, 30] sorted as strings
D. Error

Answer: C

Why: By default, sort() converts values to strings and sorts them alphabetically/lexicographically, not numerically.


Question 24

Which code correctly sorts numbers from smallest to largest?

A. numbers.sort()
B. numbers.sort((a, b) => a - b)
C. numbers.sort((a, b) => b - a)
D. numbers.numericSort()

Answer: B

Why: The compare function (a, b) => a - b sorts numbers in ascending order.


Question 25

A raccoon wants only snacks with more than 5 letters:

const snacks = ['pie', 'cookie', 'nachos']

Which method is best?

A. map()
B. filter()
C. push()
D. join()

Answer: B

Why: filter() creates a new array containing only the items that pass a condition, such as snack.length > 5.


Question 26

What does filter() return?

A. A new array with items that pass a condition
B. A single item
C. The original array changed directly
D. A string

Answer: A

Why: filter() returns a new array. It does not directly change the original array.


Question 27

A wizard wants to turn every spell into uppercase:

const spells = ['fire', 'ice', 'wind']

Which method is best?

A. filter()
B. map()
C. pop()
D. includes()

Answer: B

Why: map() is used to transform each item in an array and return a new array with the transformed values.


Question 28

What does map() return?

A. A new transformed array
B. Nothing
C. A boolean
D. The first matching item

Answer: A

Why: map() creates and returns a new array by applying a function to each item in the original array.


Question 29

A duck writes:

const sounds = ['quack', 'honk', 'meow']
const result = sounds.includes('quack')

What is result?

A. 'quack'
B. 0
C. true
D. false

Answer: C

Why: includes() checks whether an array contains a value. Since 'quack' exists in the array, it returns true.


Question 30

Which method combines array items into a string?

A. join()
B. concat()
C. push()
D. filter()

Answer: A

Why: join() combines array items into a string, optionally using a separator.


Question 31

A ghost writes:

function scare(name) {
  return `Boo, ${name}!`
}

const result = scare('Kevin')

What is stored in result?

A. Boo, Kevin!
B. undefined
C. scare Kevin
D. Boo, name!

Answer: A

Why: The function receives 'Kevin' as the argument for name and returns the template literal string Boo, Kevin!.


Question 32

What happens if a function does not have a return statement?

A. It returns false
B. It returns null
C. It returns undefined
D. It returns the last variable automatically

Answer: C

Why: In JavaScript, a function without an explicit return returns undefined.


Question 33

A raccoon writes:

function stealSnack() {
  const snack = 'cookie'
}

console.log(snack)

What happens?

A. It prints 'cookie'
B. It prints undefined
C. It causes an error because snack is local to the function
D. It creates a global variable

Answer: C

Why: The variable snack is declared inside the function, so it only exists inside that function. Trying to access it outside causes an error.


Question 34

Which statement about scope is correct?

A. Variables declared inside a function are always global
B. Variables declared inside a function are local to that function
C. Variables declared with const can be used everywhere
D. Scope only applies to arrays

Answer: B

Why: Function scope means variables declared inside a function are only available inside that function.


Question 35

A goblin updates the page:

$box.innerHTML = '<p>Gold!</p>'

What happens?

A. The text is displayed as plain text
B. The HTML inside $box is replaced
C. A new paragraph is added without removing old content
D. Nothing happens

Answer: B

Why: Assigning a value to innerHTML replaces the existing HTML content inside the selected element.


Question 36

Which code adds new HTML without removing the existing HTML?

A. $list.innerHTML = '<li>New</li>'
B. $list.innerHTML += '<li>New</li>'
C. $list.textContent = '<li>New</li>'
D. $list.classList.add('<li>New</li>')

Answer: B

Why: += appends the new HTML string to the existing innerHTML instead of replacing it completely.


Question 37

A pirate creates:

const treasure = {
  gold: 100,
  gems: 50
}

Which loop works well with Object.entries(treasure)?

A.

for (const [key, value] of Object.entries(treasure)) {}

B.

for (const treasure of Object.entries) {}

C.

for (Object.entries in treasure) {}

D.

treasure.loop()

Answer: A

Why: Object.entries(treasure) returns an array of key-value pairs. Destructuring with [key, value] lets the loop access both parts clearly.


Question 38

Which code creates a product card using a template literal?

A.

const html = '<h2>${product.title}</h2>'

B.

const html = `<h2>${product.title}</h2>`

C.

const html = '<h2>'product.title'</h2>'

D.

const html = h2(product.title)

Answer: B

Why: Template literals require backticks. The ${} syntax only evaluates variables inside backtick strings.


Question 39

A llama writes:

const animals = ['llama', 'goat', 'alpaca']
const html = animals.map(animal => `<li>${animal}</li>`)

What is html?

A. A string
B. A new array of HTML strings
C. A single <li> element
D. undefined

Answer: B

Why: map() returns a new array. In this case, each animal is transformed into an HTML string.


Question 40

Why is it better to build all HTML first and update innerHTML once?

A. It avoids unnecessary repeated DOM updates
B. It makes JavaScript slower
C. It prevents arrays from working
D. It automatically creates CSS

Answer: A

Why: Updating the DOM repeatedly can be inefficient. Building one complete HTML string first and inserting it once is cleaner and usually faster.


Part B — Code Explanation Blocks

Explain what the code does, what the output is, and why.


Code Block 1

const inventory = [
  { name: 'tiny sword', price: 12 },
  { name: 'suspicious mushroom', price: 4 },
  { name: 'golden sock', price: 25 }
]

const expensiveItems = inventory.filter(function (item) {
  return item.price > 10
})

console.log(expensiveItems)

Expected Explanation

This code creates an array of objects. Each object represents an inventory item with a name and price.

The filter() method creates a new array containing only the items where price > 10.

The result is:

[
  { name: 'tiny sword', price: 12 },
  { name: 'golden sock', price: 25 }
]

The mushroom is not included because its price is only 4.


Code Block 2

const products = [
  { title: 'Notebook', price: 5.99 },
  { title: 'Backpack', price: 49.99 },
  { title: 'Pencil', price: 1.25 }
]

const productTitles = products.map(function (product) {
  return product.title
})

console.log(productTitles)

Expected Explanation

This code uses map() to transform an array of product objects into an array of product titles.

The original array is not changed.

The output is:

['Notebook', 'Backpack', 'Pencil']

Code Block 3

const spells = {
  fireball: 10,
  invisibility: 25,
  frogMode: 5
}

let html = '<select>'

for (const [spell, cost] of Object.entries(spells)) {
  html += `<option value="${spell}">${spell} - ${cost} mana</option>`
}

html += '</select>'

console.log(html)

Expected Explanation

This code starts with an object where each key is a spell name and each value is the mana cost.

Object.entries(spells) converts the object into key-value pairs.

The for...of loop builds an HTML <select> menu with one <option> for each spell.

The final string contains a complete select menu.


Code Block 4

const products = [
  {
    title: 'Water Bottle',
    price: 14.99,
    image: 'images/bottle.webp'
  },
  {
    title: 'Lunch Bag',
    price: 11.99,
    image: 'images/lunch-bag.webp'
  }
]

const cards = []

for (const product of products) {
  cards.push(`
    <article>
      <img src="${product.image}" alt="${product.title}">
      <h2>${product.title}</h2>
      <p>$${product.price}</p>
    </article>
  `)
}

console.log(cards.join(''))

Expected Explanation

This code loops through an array of product objects.

For each product, it creates an HTML string using a template literal and pushes it into the cards array.

At the end, cards.join('') combines all HTML strings into one large string.

This is useful before inserting the result into the DOM with innerHTML.


Code Block 5

const cats = ['Mittens', 'Lord Scratch', 'Chair Destroyer']

cats[1] = 'Princess Tuna'

cats.push('Keyboard Goblin')

console.log(cats)

Expected Explanation

This code starts with an array of cat names.

The second item, at index 1, is changed from 'Lord Scratch' to 'Princess Tuna'.

Then a new item, 'Keyboard Goblin', is added to the end using push().

The output is:

['Mittens', 'Princess Tuna', 'Chair Destroyer', 'Keyboard Goblin']

Code Block 6

const cart = [
  { item: 'Mouse', price: 24.99 },
  { item: 'Keyboard', price: 79.99 },
  { item: 'Monitor', price: 199.99 }
]

let total = 0

for (const product of cart) {
  total += product.price
}

console.log(total)

Expected Explanation

This code calculates the total cost of items in a shopping cart.

It starts total at 0.

The for...of loop goes through each product object in the cart and adds the product price to total.

The final output is:

304.97

Code Block 7

const dragon = {
  name: 'Noodles',
  dangerLevel: 9000,
  hobbies: ['flying', 'napping', 'tax evasion']
}

console.log(dragon.name)
console.log(dragon.hobbies[1])

Expected Explanation

This code creates an object representing a dragon.

The object has:

  • a name property
  • a dangerLevel property
  • a hobbies property containing an array

dragon.name accesses the dragon’s name.

dragon.hobbies[1] accesses the second item in the hobbies array.

The output is:

Noodles
napping

Code Block 8

const students = [
  { name: 'Aisha', grade: 82 },
  { name: 'Mateo', grade: 58 },
  { name: 'Lina', grade: 91 },
  { name: 'Noah', grade: 64 }
]

const passingStudents = students.filter(function (student) {
  return student.grade >= 60
})

const names = passingStudents.map(function (student) {
  return student.name
})

console.log(names)

Expected Explanation

This code first filters the students to keep only those with a grade of 60 or higher.

Then it uses map() to create a new array containing only the names of the passing students.

The output is:

['Aisha', 'Lina', 'Noah']

Mateo is excluded because the grade is 58.


Code Block 9

const $message = document.getElementById('message')

const ghost = {
  name: 'Sir Booington',
  mood: 'dramatic'
}

$message.innerHTML = `
  <h2>${ghost.name}</h2>
  <p>The ghost is feeling ${ghost.mood} today.</p>
`

Expected Explanation

This code selects an HTML element with the ID message.

It creates an object called ghost with two properties: name and mood.

Then it uses a template literal to create HTML and insert it into the selected element using innerHTML.

The page will display:

  • a heading with Sir Booington
  • a paragraph saying the ghost is feeling dramatic

Code Block 10

const product = {
  title: 'Maple Leaf T-Shirt',
  materials: {
    cotton: 7.99,
    polyester: 8.99,
    blend: 9.49
  }
}

let options = ''

for (const [material, price] of Object.entries(product.materials)) {
  options += `
    <option value="${material}">
      ${material} - $${price.toFixed(2)}
    </option>
  `
}

console.log(options)

Expected Explanation

This code creates a product object with a nested materials object.

Each material has a price.

Object.entries(product.materials) converts the materials object into key-value pairs.

The loop creates an <option> element for each material.

toFixed(2) formats the price with two decimal places.

The final result is an HTML string containing three option elements:

  • cotton - $7.99
  • polyester - $8.99
  • blend - $9.49

Source: Midterm Evaluation Previewopen in new window