JavaScript Arrays & Basic Array Methods Quiz

JavaScript
0 Passed
0% acceptance

Tackle 100 JavaScript array questions that range from everyday indexing to tricky splice mutations and iteration strategies. Forty questions supply runnable code so you can reason through exact behaviour before answering.

100 Questions
~200 minutes
1

Question 1

A release engineer maintains a meeting agenda stored in an array. After adding and removing a few checkpoints, what string is printed by the tooling that summarises the remaining agenda items?

javascript
const schedule = ['kickoff', 'standup']
schedule.push('retro')
schedule.pop()
schedule.push('demo')
console.log(schedule.join(','))
A
kickoff,standup
B
kickoff,standup,demo
C
kickoff,demo
D
demo,standup
2

Question 2

A customer success dashboard keeps a rolling queue of priorities. After the support system prepends a hotfix and the oldest entry is removed, what does the monitor display for the queue headline?

javascript
const queue = ['renewal', 'expansion']
queue.shift()
queue.unshift('hotfix')
console.log(`${queue[0]}:${queue.length}`)
A
hotfix:2
B
renewal:2
C
expansion:1
D
renewal:1
3

Question 3

While investigating copy-on-write behaviour, a developer clones an array before mutation. What lengths are reported for the original versus the clone after the mutation is performed?

javascript
const data = [1, 2, 3]
const copy = data.slice()
copy.push(4)
console.log(`${data.length}-${copy.length}`)
A
3-3
B
3-4
C
4-4
D
4-3
4

Question 4

A data-cleanup script trims off a header row before adding a calculated value at the end. What does the final console output show?

javascript
const rows = ['header', 'rowA', 'rowB']
rows.shift()
rows.push('summary')
console.log(rows)
A
['rowA', 'rowB', 'summary']
B
['header', 'rowA', 'summary']
C
['rowA', 'summary', 'rowB']
D
['summary', 'rowA', 'rowB']
5

Question 5

An analytics engineer slices a production array to isolate the first three events before mutating them. Which string is produced when the isolated slice is rendered?

javascript
const events = ['login', 'view', 'click', 'logout']
const important = events.slice(0, 3)
important.splice(1, 1, 'hover')
console.log(important.join(' > '))
A
login > hover > click
B
login > view > click
C
view > hover > click
D
login > view > hover
6

Question 6

In a load-testing harness, the team removes duplicate hosts using indexOf before pushing an only-if-missing entry. Which status string is logged?

javascript
const hosts = ['edge-1', 'edge-2', 'edge-1']
const cleaned = []
for (const host of hosts) {
  if (cleaned.indexOf(host) === -1) cleaned.push(host)
}
console.log(`${cleaned.length}:${cleaned.includes('edge-2')}`)
A
2:true
B
3:false
C
2:false
D
1:true
7

Question 7

A feature flag loader splices in a fallback flag before slicing to the last two entries. What JSON string is ultimately displayed to telemetry?

javascript
const flags = ['alpha', 'beta', 'gamma']
flags.splice(1, 0, 'fallback')
const recent = flags.slice(-2)
console.log(JSON.stringify(recent))
A
["fallback","beta"]
B
["gamma"]
C
["beta","gamma"]
D
["fallback","gamma"]
8

Question 8

While watching a replay, the monitoring service unshifts the latest anomaly and pops if the buffer grows beyond three entries. What remains inside the buffer snapshot?

javascript
const anomalies = ['A12', 'B04']
anomalies.unshift('Z99')
anomalies.push('C01')
if (anomalies.length > 3) anomalies.pop()
console.log(anomalies)
A
['Z99', 'A12', 'B04']
B
['Z99', 'A12', 'C01']
C
['A12', 'B04', 'C01']
D
['B04', 'C01']
9

Question 9

A build pipeline converts an array to a human-readable sentence after augmenting metadata. What final string is printed?

javascript
const steps = ['compile', 'bundle']
steps.unshift('lint')
steps.push('deploy')
const summary = steps.join(' -> ')
console.log(summary)
A
compile -> bundle -> deploy
B
lint -> compile -> bundle -> deploy
C
lint -> compile -> bundle
D
deploy -> bundle -> compile
10

Question 10

A QA engineer instruments array iteration to compute the latency budget consumed by each stage. What numeric tuple is printed to the console?

javascript
const stages = [12, 7, 5]
let total = 0
for (const ms of stages) {
  total += ms
}
console.log(`${stages.length}:${total}`)
A
3:24
B
3:18
C
2:19
D
3:17
11

Question 11

A log aggregator copies the first two entries, mutates the clone, and compares both arrays. What values appear when the diagnostic statement executes?

javascript
const logs = ['info', 'warn', 'error']
const subset = logs.slice(0, 2)
subset.push('debug')
console.log(logs[2], subset[2])
A
error debug
B
debug debug
C
error error
D
warn debug
12

Question 12

During a migration, stale feature toggles are removed with splice before adding a guard rail. What array snapshot is logged?

javascript
const toggles = ['payments', 'beta', 'legacy', 'audit']
toggles.splice(1, 2, 'guard')
console.log(toggles)
A
['payments', 'guard', 'audit']
B
['payments', 'beta', 'guard', 'audit']
C
['guard', 'legacy', 'audit']
D
['payments', 'guard']
13

Question 13

A telemetry signal clears room in a buffer by popping the last value if more than three anomalies are present after a new one is appended. Which number prints?

javascript
const metrics = [3, 5, 8]
metrics.push(13)
if (metrics.length > 3) metrics.pop()
console.log(metrics.length)
A
2
B
3
C
4
D
5
14

Question 14

A content pipeline merges two tags lists and needs to know whether the original tag array mutated. What line is printed?

javascript
const tags = ['news', 'tech']
const merged = tags.concat(['ai', 'cloud'])
console.log(`${tags.length}:${merged.length}`)
A
2:4
B
4:4
C
2:2
D
4:2
15

Question 15

In a resilience test, the array buffer is cleared by setting length to zero before new items are appended. What is reported after the operations?

javascript
const buffer = ['a', 'b', 'c']
buffer.length = 0
buffer.push('d')
console.log(buffer)
A
['d']
B
['a', 'd']
C
['a', 'b', 'c', 'd']
D
[]
16

Question 16

A metrics reporter reads array length inside a loop that shifts processed items. What string appears after processing two samples?

javascript
const samples = [10, 20, 30]
let processed = 0
while (samples.length) {
  samples.shift()
  processed++
  if (processed === 2) break
}
console.log(`${processed}:${samples.length}`)
A
2:1
B
2:0
C
3:0
D
1:2
17

Question 17

A documentation generator reverses an array via slice and reverse to keep the original intact. What summary line is printed?

javascript
const changelog = ['v1', 'v1.1', 'v1.2']
const reversed = changelog.slice().reverse()
console.log(`${changelog[0]}|${reversed[0]}`)
A
v1|v1.2
B
v1.2|v1
C
v1|v1
D
v1.2|v1.2
18

Question 18

A troubleshooting script rebuilds an array via spread syntax to append new log lines while leaving the source intact. What does the comparison report?

javascript
const source = ['init', 'ready']
const combined = [...source, 'error', 'recover']
console.log(source.length === combined.length)
A
true
B
false
C
undefined
D
It throws a TypeError
19

Question 19

A diagnostics report tracks which indices were mutated during a cleanup by pairing indexOf lookups with splice. What tuple is logged?

javascript
const issues = ['E02', 'E14', 'E07', 'E14']
const first = issues.indexOf('E14')
issues.splice(first, 1)
const second = issues.indexOf('E14')
console.log(`${first}|${second}`)
A
1|2
B
2|3
C
1|3
D
1|-1
20

Question 20

A data pipeline flattens the first two nested arrays by concatenating them before computing the resulting length. What number prints?

javascript
const batches = [[1, 2], [3, 4], [5]]
const combined = batches[0].concat(batches[1])
console.log(combined.length)
A
2
B
3
C
4
D
5
21

Question 21

During rollback analysis, an engineer inspects an array copy constructed with Array.from before pushing a new marker. Which two markers appear?

javascript
const releases = ['1.0', '1.1']
const copy = Array.from(releases)
copy.push('rollback')
console.log(releases[1], copy[2])
A
1.1 rollback
B
rollback rollback
C
1.0 rollback
D
1.1 1.1
22

Question 22

An experiment calculates running totals using forEach alongside manual indexing. After the loop completes, what string leaves the console?

javascript
const values = [2, 4, 6]
let total = 0
values.forEach((value, index) => {
  total += value * (index + 1)
})
console.log(total)
A
28
B
24
C
20
D
18
23

Question 23

A refactor introduces Array.isArray checks to guard multi-source inputs. What boolean pair prints?

javascript
const maybeList = JSON.parse('[1,2,3]')
const status = [Array.isArray(maybeList), Array.isArray(maybeList[0])]
console.log(status.join(','))
A
true,false
B
true,true
C
false,true
D
false,false
24

Question 24

Support tools frequently remove the first alert after rendering it. With a combination of shift and length arithmetic, what value is logged?

javascript
const alerts = ['critical', 'major', 'minor']
const first = alerts.shift()
console.log(`${first}-${alerts.length}`)
A
critical-2
B
major-2
C
critical-3
D
major-1
25

Question 25

A scheduler reorganises tasks by removing the first day's jobs and pre-pending a planning phase. After the adjustments, what is displayed?

javascript
const sprint = ['Mon: dev', 'Tue: qa', 'Wed: release']
sprint.shift()
sprint.unshift('Plan')
console.log(sprint.join(' | '))
A
Plan | Tue: qa | Wed: release
B
Mon: dev | Plan | Tue: qa | Wed: release
C
Plan | Wed: release
D
Tue: qa | Wed: release
26

Question 26

A backend utility merges multiple arrays and then truncates to a maximum of five items using length manipulation. What string is printed?

javascript
const a = ['a1', 'a2']
const b = ['b1', 'b2', 'b3']
const merged = a.concat(b)
merged.length = 5
console.log(merged.join(','))
A
a1,a2,b1,b2,b3
B
a1,a2,b1,b2
C
a1,a2,b1,b2,undefined
D
a1,a2
27

Question 27

A support script repairs a queue by inserting an escalated ticket before the last two items. Which array snapshot is logged?

javascript
const queue = ['T1', 'T2', 'T3', 'T4']
queue.splice(queue.length - 2, 0, 'Escalated')
console.log(queue)
A
['T1', 'T2', 'Escalated', 'T3', 'T4']
B
['T1', 'T2', 'T3', 'Escalated', 'T4']
C
['Escalated', 'T1', 'T2', 'T3', 'T4']
D
['T1', 'T2', 'T3', 'T4', 'Escalated']
28

Question 28

A watchdog timer rotates through an array by shifting the first element, pushing it to the end, and printing the new head. Which value is announced?

javascript
const rotation = ['north', 'east', 'south', 'west']
const head = rotation.shift()
rotation.push(head)
console.log(rotation[0])
A
north
B
east
C
south
D
west
29

Question 29

A devtools extension captures the last two commits only if more than two exist. After slice runs, what JSON snippet appears?

javascript
const commits = ['c1', 'c2', 'c3', 'c4']
const subset = commits.length > 2 ? commits.slice(-2) : commits
console.log(JSON.stringify(subset))
A
["c3","c4"]
B
["c1","c2"]
C
["c2","c3"]
D
["c1","c2","c3","c4"]
30

Question 30

A content pipeline calculates the first index of a marker and the last index using indexOf and lastIndexOf. Which tuple is printed?

javascript
const markers = ['start', 'mid', 'mid', 'end']
console.log(`${markers.indexOf('mid')},${markers.lastIndexOf('mid')}`)
A
1,2
B
1,1
C
2,2
D
0,1
31

Question 31

A deployment script ensures the first element exists before reading from index 0. After combining push and a fallback, which log line appears?

javascript
const stack = []
if (!stack.length) stack.push('bootstrap')
stack.push('deploy')
console.log(stack[0] + '/' + stack.length)
A
bootstrap/2
B
deploy/1
C
bootstrap/1
D
deploy/2
32

Question 32

A reliability check assembles a command by joining array elements with spaces only after verifying they are strings. What command string is produced?

javascript
const parts = ['npm', 'run', 'build']
const isValid = parts.every(part => typeof part === 'string')
console.log(isValid ? parts.join(' ') : 'INVALID')
A
npm run build
B
INVALID
C
npm,run,build
D
npm run
33

Question 33

During data normalisation, undefined values are filtered out before the array is stringified. What string prints?

javascript
const readings = [undefined, 'ok', undefined, 'warn']
const filtered = readings.filter(Boolean)
console.log(filtered.join('|'))
A
ok|warn
B
undefined|ok|warn
C
ok|undefined|warn
D
ok|warn|undefined
34

Question 34

A regression test concatenates two arrays and checks whether the original array object reference changed. What boolean prints?

javascript
const primary = ['p1', 'p2']
const combined = primary.concat(['p3'])
console.log(primary === combined)
A
true
B
false
C
undefined
D
Throws TypeError
35

Question 35

A lab script stores sensor names and rotates them monthly by removing the first and adding a new one at the front. What array is printed?

javascript
const sensors = ['north', 'south', 'east']
sensors.shift()
sensors.unshift('west')
console.log(sensors)
A
['west', 'south', 'east']
B
['north', 'south', 'east']
C
['west', 'north', 'south', 'east']
D
['south', 'east']
36

Question 36

A payment reconciliation tool slices off trailing adjustments if more than four entries exist after a splice injects a placeholder. What set of adjustments logs?

javascript
const adjustments = ['fee', 'tax', 'discount', 'credit']
adjustments.splice(2, 0, 'placeholder')
const trimmed = adjustments.slice(0, 4)
console.log(trimmed)
A
['fee', 'tax', 'placeholder', 'discount']
B
['fee', 'tax', 'discount', 'credit']
C
['placeholder', 'discount', 'credit']
D
['fee', 'tax', 'placeholder', 'credit']
37

Question 37

A mobile app caches three most recent searches by pushing and then slicing. After inserting a new term, what string prints?

javascript
const searches = ['router', 'switch', 'firewall']
searches.push('access point')
const recent = searches.slice(-3)
console.log(recent.join(', '))
A
switch, firewall, access point
B
router, switch, firewall
C
router, switch, access point
D
firewall, access point
38

Question 38

A data science notebook reads the length difference between two arrays after push and pop operations. What numeric difference shows?

javascript
const base = [1, 2, 3]
const test = base.slice()
test.push(4, 5)
test.pop()
console.log(test.length - base.length)
A
1
B
2
C
0
D
-1
39

Question 39

An experimentation rig lazily creates a queue with push and shift, then ensures the queue never exceeds two entries by popping as needed. What array is printed?

javascript
const queue = []
queue.push('task-1')
queue.push('task-2')
queue.push('task-3')
while (queue.length > 2) {
  queue.shift()
}
console.log(queue)
A
['task-2', 'task-3']
B
['task-1', 'task-2']
C
['task-3']
D
['task-1', 'task-3']
40

Question 40

A code review tool simulates the addition of a missing import at the start of an array containing statements, then pops the last entry to keep the snippet concise. What result is logged?

javascript
const statements = ['console.log('ready')', 'runTests()']
statements.unshift('import { runTests } from './tests')
statements.push('cleanup()')
statements.pop()
console.log(statements.length)
A
2
B
3
C
4
D
1
41

Question 41

Your team shares a utility function that always treats the first array element as the canonical label. In a code review, you notice a contributor repeatedly calls shift to remove "placeholder" before reading index 0. Explain which method better communicates the intent and why.

A
Use slice(1) to return a new array without the placeholder so the original remains intact.
B
Use pop so the placeholder is removed while keeping the remainder of the array untouched.
C
Use unshift to add the label you want instead of removing the placeholder.
D
No change—shift is the only method that supports this behaviour.
42

Question 42

You inherit an onboarding wizard that pushes optional steps into an array and later uses the first index to display the kickoff screen. How would you guard against the wizard showing a blank state when no steps are added?

A
Check array length before indexing and supply a default description when the array is empty.
B
Convert the array to a string with join so the first index is never undefined.
C
Call pop before rendering the first step to ensure a valid item remains.
D
Use splice(0, 1) to remove the missing step.
43

Question 43

A senior engineer is refactoring inventory management logic. They suggest replacing a manual for loop with for…of when iterating product SKUs. What is the strongest reason to accept the change?

A
for…of expresses intent to iterate values directly, reducing index bugs and improving readability.
B
for…of executes faster than a for loop in every JavaScript engine.
C
for…of automatically deduplicates items, so duplicates disappear without extra code.
D
for…of implicitly clones the array, so product mutations are isolated.
44

Question 44

During a postmortem, you find code that repeatedly calls Array.isArray before pushing items, even though the variable is declared as an array literal. Which improvement should you propose?

A
Remove the redundant checks and rely on static typing or contract tests for validation.
B
Replace Array.isArray with typeof === "array" for better performance.
C
Call toString() first to ensure the value is serialised.
D
Switch to using Set so the type check becomes unnecessary.
45

Question 45

A growth experiment logs product impressions by pushing IDs into an array and later slicing the last 50 items. Under heavy load, the array can grow to hundreds of thousands of entries. How can you keep memory usage predictable without losing the most recent impressions?

A
After each push, check length and shift the first element when the array exceeds 50.
B
Use pop after every push to keep the array steady.
C
Call splice(50) once at initialisation to freeze the array size.
D
Convert the array to a string after each push so it cannot grow in memory.
46

Question 46

Your data team requires a non-mutating operation when trimming weekly metrics to the first seven days. Which array method satisfies the requirement while keeping the original data intact?

A
slice(0, 7)
B
splice(0, 7)
C
shift() seven times
D
pop() until length equals seven
47

Question 47

You review a function that removes a specific user ID from an audit list. The code finds the index with indexOf, checks if it is -1, and then calls splice to remove the ID. What edge case still needs handling?

A
The audit list might contain multiple occurrences of the same user ID.
B
splice cannot remove the only element in an array.
C
indexOf returns NaN if the item is not found, breaking the check.
D
splice will convert the array into a Set automatically.
48

Question 48

A junior developer uses pop inside a for loop that iterates from index 0 to length to remove trailing noise data. Why will this loop malfunction?

A
Mutating length with pop while relying on an increasing index causes you to skip elements or hit undefined entries.
B
pop throws an error inside loops.
C
Arrays cannot be mutated inside a loop.
D
pop removes the first element instead of the last.
49

Question 49

A data export system concatenates arrays of records and then uses join(' ') to create a line-delimited payload. What risk should you highlight in the design review?

A
join converts non-string elements using toString, which could produce unsuitable text for complex objects.
B
join cannot be used with newline separators.
C
concat mutates the original arrays, so records disappear.
D
Array length doubles when join is called.
50

Question 50

You need to compare two arrays to ensure they reference the same object before mutating them. Which approach preserves correctness and keeps the intent obvious?

A
Use the === operator to compare references before modifying the array.
B
Compare join results, since matching strings prove identity.
C
Slice both arrays to length 0 and push a sentinel value.
D
Spread both arrays into a Set and compare sizes.
51

Question 51

An observability team wants to retain the last five emitted events. They currently append with push and remove the oldest entry with shift inside the same tick. Evaluate the time complexity and propose an optimisation if this occurs millions of times per day.

A
shift is O(n); consider tracking a moving index or using a circular buffer to avoid array re-indexing.
B
push is O(n); switch to unshift to improve performance.
C
Both push and shift are O(1); no optimisation is necessary.
D
splice is faster than both push and shift for this case.
52

Question 52

You need to clone an array of configuration objects so the clone can be mutated without touching production defaults. Which approach best communicates the requirement?

A
Use map or slice to produce a new array, and deep clone entries if they contain nested objects.
B
Use concat with no arguments; it mutates the original into a clone.
C
Assign the array to a new variable because arrays copy by value.
D
Call pop and push on the original to force a clone.
53

Question 53

A teammate sorts an array in place before slicing the first three elements. How do you make it clear in the code review that the original order is important elsewhere?

A
Request using slice().sort() to avoid mutating the original array before slicing.
B
Recommend join instead of sort to retain order.
C
Suggest using indexOf for sorting.
D
Explain that sort clones automatically, so no action is needed.
54

Question 54

When logging array state for debugging, why might JSON.stringify yield clearer results than join?

A
JSON.stringify exposes nested structures and differentiates between numbers, strings, and objects.
B
join always throws with nested arrays.
C
JSON.stringify converts arrays into Set objects automatically.
D
join mutates the array, so JSON.stringify is safer.
55

Question 55

Product operations wants to run a nightly job that removes the first and last elements from a backlog only if the backlog exceeds five items. Which combination of methods keeps the logic succinct?

A
Check length > 5, then call shift and pop once each to trim the ends.
B
Use slice to grab the middle three items and assign back in place.
C
Call splice twice at index 0.
D
Reverse the array and call pop twice.
56

Question 56

A bug report shows that a helper mutates the array passed into it when deduplicating via splice. Why might returning a filtered copy be safer in asynchronous workflows?

A
Mutating shared arrays can create race conditions if other consumers read while deduplication occurs.
B
splice cannot run inside async functions.
C
filter ignores duplicate elements by design.
D
Returning copies is slower than mutation, so it must be correct.
57

Question 57

When documenting API payloads, you note that a handler calls join on a list of tags to produce a comma-separated string but the API consumers expected an array. What is the best remediation plan?

A
Return the array directly and let consumers call join if they want a string.
B
Continue joining but document the change as a breaking contract update.
C
Convert the array into a Map for richer semantics.
D
Drop support for the endpoint.
58

Question 58

A release engineer needs to insert a maintenance notice at the start of a message queue without disturbing order. Why is unshift the ideal choice?

A
unshift inserts at index 0, shifting the rest forward while preserving relative ordering.
B
unshift removes the first element and replaces it.
C
unshift clones the array before mutation, avoiding side effects.
D
unshift runs in O(1) regardless of array size.
59

Question 59

You are reviewing code that converts arguments objects into arrays via Array.prototype.slice.call. What modern alternative improves clarity and reduces boilerplate?

A
Use Array.from(arguments) or the rest parameter syntax.
B
Use join on arguments.
C
Use splice to copy arguments.
D
Use pop to remove arguments.
60

Question 60

A developer sorts user IDs, but the product team insists that the original array order must remain stable for audit playback. Which minimal change preserves audit fidelity?

A
Call slice() before sort to clone the array, then work with the sorted copy.
B
Reverse the array after sorting to undo the mutation.
C
Use join so the array cannot be mutated.
D
Use indexOf to reorder elements manually.
61

Question 61

Your array summariser must display "No records" when the dataset is empty and otherwise show `first (length items total)`. How would you implement this using only length and indexing checks?

A
If length is 0 log "No records"; otherwise log `${array[0]} (${array.length} items total)`.
B
Always log the first element and rely on undefined to convey emptiness.
C
Call pop to get the first element and then log length.
D
Call join to log all entries regardless of emptiness.
62

Question 62

A performance dashboard computes whether two arrays share the same first element before merging. Why is comparing array[0] sufficient and faster than indexOf for this use case?

A
Accessing index 0 is O(1); indexOf scans the array until it finds the value.
B
indexOf mutates the array.
C
indexOf throws when the element is missing.
D
indexOf only works on strings.
63

Question 63

Your CI pipeline receives arrays of failing test IDs. If the array is empty, you must skip the expensive rerun step. Which guard most clearly expresses this intent?

A
if (!failures.length) return; // Nothing to rerun
B
if (failures === []) return;
C
if (failures.join() === "") return;
D
if (failures.pop()) return;
64

Question 64

A developer attempts to remove multiple indices using a for loop with splice(i, 1). Why should they iterate from the end of the array instead of the beginning?

A
Iterating from the end prevents index shifting issues that cause elements to be skipped.
B
splice cannot be called with low indices.
C
forward iteration throws an exception.
D
splice clones the array when called from the end.
65

Question 65

When merging analytics datasets, you must avoid duplicates while keeping order stable. Which array method combination is cleanest?

A
Use filter with indexOf to keep only the first occurrence of each value.
B
Use reverse to remove duplicates.
C
Use pop to drop duplicates.
D
Use join to remove duplicates as strings.
66

Question 66

You must determine whether a given value is the last element in an array without mutating it. Which expression communicates the intent best?

A
value === array[array.length - 1]
B
array.pop() === value
C
array.shift() === value
D
array.splice(-1) === value
67

Question 67

A report generator needs a copy of the first ten rows but must leave the original dataset untouched for subsequent analytics. Which statement summarises the best approach?

A
Use dataset.slice(0, 10) to build a shallow copy of the first ten rows.
B
Use dataset.splice(0, 10) so the copy and original stay in sync.
C
Use dataset.pop() repeatedly to copy elements.
D
Use dataset.join() to create the copy.
68

Question 68

During incident response, you must quickly check whether a response buffer includes a "timeout" marker. Which method yields the best blend of performance and clarity?

A
buffer.includes("timeout")
B
buffer.indexOf("timeout") > -1
C
buffer.join().includes("timeout")
D
buffer.shift() === "timeout"
69

Question 69

A monitoring script empties an array by setting length = 0 before pushing new entries. Why should you document this behaviour?

A
Because length assignment irreversibly removes data; documenting it prevents accidental reuse of the truncated array.
B
Because length assignment throws an exception.
C
Because push fails after length is set to zero.
D
Because length only affects join.
70

Question 70

You evaluate code that pushes values into an array inside setInterval without ever removing them. What long-term issue should you flag?

A
Unbounded growth causes memory leaks; implement a cap or clear the array periodically.
B
push eventually throws after 2^32 elements.
C
push is not safe inside setInterval.
D
Arrays automatically drop old elements when memory is full.
71

Question 71

The UX team wants to display the number of items removed by a bulk archive operation implemented with splice. How can you capture this value without running an extra loop?

A
Store the array returned by splice; its length equals the number of removed items.
B
Call join on the removed items.
C
Use shift instead of splice to count.
D
Use Array.from to count removed items.
72

Question 72

While debugging, you discover a helper that copies values from one array to another by iterating indices manually. Which built-in feature can simplify this logic?

A
Use spread syntax: const copy = [...original];
B
Use join to copy values.
C
Use pop to copy values.
D
Use indexOf to copy values.
73

Question 73

Your array-processing pipeline needs to remove falsy values but keep zeros. Why is filter(Boolean) insufficient, and what alternative should you prefer?

A
Boolean removes zeros because they are falsy; use a predicate that explicitly checks for undefined or null instead.
B
Boolean cannot be used in filter.
C
Boolean converts everything to strings first.
D
Boolean throws when encountering objects.
74

Question 74

A lead engineer warns that using splice within a forEach callback can lead to confusing results. Why?

A
splice mutates the array while forEach keeps incrementing the index, so elements can be skipped or processed twice.
B
splice throws inside forEach.
C
forEach disallows mutations.
D
splice clones the array before finishing.
75

Question 75

When validating API responses, you need to confirm the payload is an array of at least two elements before accessing positions 0 and 1. Which guard is the clearest?

A
Array.isArray(payload) && payload.length >= 2
B
payload === [] && payload.length >= 2
C
payload.join() !== ""
D
payload.shift() && payload.unshift()
76

Question 76

You encounter code that repeatedly calls indexOf inside a loop to determine whether to push elements into a result array. How can Set improve both readability and performance?

A
Convert the source array to a Set and then iterate, checking resultSet.has(value) before adding.
B
Use Set to automatically sort values.
C
Use Set because it prevents iteration altogether.
D
Use Set to join values.
77

Question 77

Why might you prefer to accumulate results with reduce when computing grouped statistics from an array of records?

A
reduce collects results in a single pass while leaving the original array untouched, clarifying aggregation intent.
B
reduce clones the array before running.
C
reduce runs only on numeric arrays.
D
reduce automatically skips null entries.
78

Question 78

Your array stores route segments such as `'GET /users'`. You need to derive the last segment of each route without modifying the original data. Which combination communicates intent?

A
routes.map(route => route.split(" ")[1].split("/").pop())
B
routes.shift()
C
routes.splice(0, routes.length)
D
routes.join("/")
79

Question 79

While porting code from another language, a developer attempts to use negative indices directly (array[-1]) to access the last element. Why is this problematic in JavaScript arrays?

A
Negative indices create object properties rather than array elements, so the last element is not returned.
B
JavaScript throws a SyntaxError for negative indices.
C
array[-1] always equals undefined because arrays cannot hold negative values.
D
Negative indices reverse the array silently.
80

Question 80

Why is it important to avoid mutating the array passed into a React component via props when preparing derived state?

A
Mutating props breaks the expectation of one-way data flow, potentially causing stale renders or missed updates.
B
React throws when props are mutated.
C
Arrays cannot be used in React props.
D
Props always deep clone their values.
81

Question 81

You observe that combining splice and push in a single statement makes code harder to read. What rewrite keeps operations readable while preserving behaviour?

A
Separate each mutation onto its own line with descriptive comments or helper functions.
B
Wrap them in a join call.
C
Call splice twice instead of once.
D
Replace both with indexOf.
82

Question 82

When would you favour using Array.from over spread syntax to create an array from an iterable?

A
When you need to map or transform elements during creation using Array.from's second argument.
B
When the iterable contains more than 100 elements.
C
When the iterable is already an array.
D
When you want to mutate the original iterable.
83

Question 83

A query builder accumulates filters in an array and later joins them with AND. What is the main benefit of storing filters as an array instead of concatenating strings on the fly?

A
Arrays keep each filter isolated, allowing you to add, remove, or inspect filters without string parsing.
B
Arrays automatically deduplicate filters.
C
Arrays use less memory than strings.
D
Arrays sort filters alphabetically.
84

Question 84

Why might you choose splice over slice when building an undo stack for destructive operations?

A
splice modifies the array in place, letting you remove and record changes simultaneously.
B
splice returns immutable snapshots.
C
slice cannot operate on arrays larger than 32 elements.
D
splice is always faster than slice.
85

Question 85

A financial report builds month-over-month comparisons by sliding a window over array data. Which approach avoids repeated slice allocations while still providing read clarity?

A
Track start and end indices manually instead of slicing, and read values via array[index].
B
Use slice inside every iteration regardless of cost.
C
Use pop to drop old months.
D
Use join to compare months.
86

Question 86

When would using findIndex be more expressive than indexOf?

A
When you need to locate an element based on a predicate rather than exact equality.
B
When you only store strings.
C
When you need to mutate the array during lookup.
D
When you want reference equality.
87

Question 87

Your batching logic uses slice(start, end) to process a subset of records. Why is it important to document that end is non-inclusive?

A
Because off-by-one errors are common; clarifying that end is exclusive prevents processing too many or too few items.
B
Because slice throws when end equals length.
C
Because slice mutates the array when end is inclusive.
D
Because slice removes elements when end is exclusive.
88

Question 88

Why might you prefer to use destructuring assignment `const [first, ...rest] = array` in place of manually shifting the first element?

A
Destructuring is concise, avoids mutating the array, and makes the relationship between first and rest explicit.
B
Destructuring clones nested arrays.
C
Destructuring is the only way to access the first element.
D
Destructuring automatically sorts the rest.
89

Question 89

When building pagination, why is it safer to compute slice offsets from page size rather than relying on array.splice to fetch a page?

A
splice removes items, which could cause later pages to skip data or return fewer entries.
B
slice is forbidden for pagination.
C
splice gets slower with larger page numbers.
D
splice sorts the results.
90

Question 90

While reviewing logs, you note code that builds a new array by checking each entry with if (!result.includes(value)) result.push(value). Why might you replace this with a Set before converting back to an array?

A
A Set handles membership checks in O(1) time and communicates deduplication intent clearly.
B
Set automatically sorts entries.
C
Set clones the data on construction, preserving immutability.
D
Set disallows strings.
91

Question 91

Why should you avoid using delete array[index] when removing elements?

A
delete leaves a hole (empty slot) in the array; splice removes the element and shifts remaining values.
B
delete throws on arrays.
C
delete sorts the array automatically.
D
delete pops elements from the end.
92

Question 92

A script repeatedly calls unshift on large arrays to add history entries. Which alternative reduces the cost of reindexing all elements?

A
Append with push and track a rolling window, removing older entries with shift only when necessary.
B
Use join to append entries.
C
Use length = 0 before unshift.
D
Use reverse to add entries faster.
93

Question 93

When computing moving averages, why might you precompute prefix sums rather than repeatedly calling slice and reduce?

A
Prefix sums let you compute any window sum in O(1) time, avoiding repeated traversal.
B
slice and reduce are incorrect for moving averages.
C
Prefix sums mutate the array less.
D
Prefix sums automatically remove outliers.
94

Question 94

You find a loop that constructs HTML by joining array entries with a template string. Why might you switch to map + join for readability?

A
map expresses the transformation of each entry before join combines them, keeping logic declarative.
B
map mutates the original array before joining.
C
join alone cannot handle strings.
D
map is faster than loops.
95

Question 95

When building alert emails, you must ensure the subject line remains stable even if the array of contributing events is mutated later. How can you guarantee this?

A
Capture the subject as a separate string immediately (via join or template) rather than storing a reference to the array.
B
Store the array reference and rely on mutation ordering.
C
Use splice to remove mutated entries.
D
Use Array.isArray before building the subject.
96

Question 96

A data import pipeline must guarantee stable order but also deduplicate entries. What pattern achieves both goals?

A
Iterate through the array, pushing into a result array only when indexOf returns -1.
B
Sort first, then pop duplicates.
C
Use reverse to deduplicate.
D
Join the array into a string and split back.
97

Question 97

Your system merges user roles from multiple services. Some services return null instead of an array. How do you normalise the data before concatenation?

A
Treat falsy values as an empty array: const safe = Array.isArray(input) ? input : [];
B
Call join on the input.
C
Call pop on the input until it becomes an array.
D
No normalisation is needed.
98

Question 98

Why is it beneficial to define array operations in small helper functions (e.g., addItem(list, item)) when collaborating in large teams?

A
Helpers centralise mutation logic, making it easier to audit changes, add instrumentation, and enforce invariants.
B
Helpers make arrays immutable.
C
Helpers automatically deduplicate arrays.
D
Helpers run faster than native methods.
99

Question 99

A security scanner must compare two arrays of permissions for equality. Why is comparing JSON.stringify outputs risky?

A
Stringification fails if the order differs even when permissions are equivalent sets.
B
JSON.stringify mutates arrays.
C
JSON.stringify runs in O(1).
D
JSON.stringify skips undefined values.
100

Question 100

When constructing long-running queues, why is it safer to copy arrays before handing them to third-party libraries?

A
Copies prevent third-party code from mutating your internal data structures unexpectedly.
B
Third-party code cannot access arrays by contract.
C
Copiess automatically deep clone nested objects.
D
Copying arrays guarantees thread safety.

QUIZZES IN JavaScript