JavaScript Arrays & Basic Array Methods Quiz
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.
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?
const schedule = ['kickoff', 'standup']
schedule.push('retro')
schedule.pop()
schedule.push('demo')
console.log(schedule.join(','))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?
const queue = ['renewal', 'expansion']
queue.shift()
queue.unshift('hotfix')
console.log(`${queue[0]}:${queue.length}`)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?
const data = [1, 2, 3]
const copy = data.slice()
copy.push(4)
console.log(`${data.length}-${copy.length}`)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?
const rows = ['header', 'rowA', 'rowB']
rows.shift()
rows.push('summary')
console.log(rows)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?
const events = ['login', 'view', 'click', 'logout']
const important = events.slice(0, 3)
important.splice(1, 1, 'hover')
console.log(important.join(' > '))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?
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')}`)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?
const flags = ['alpha', 'beta', 'gamma']
flags.splice(1, 0, 'fallback')
const recent = flags.slice(-2)
console.log(JSON.stringify(recent))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?
const anomalies = ['A12', 'B04']
anomalies.unshift('Z99')
anomalies.push('C01')
if (anomalies.length > 3) anomalies.pop()
console.log(anomalies)Question 9
A build pipeline converts an array to a human-readable sentence after augmenting metadata. What final string is printed?
const steps = ['compile', 'bundle']
steps.unshift('lint')
steps.push('deploy')
const summary = steps.join(' -> ')
console.log(summary)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?
const stages = [12, 7, 5]
let total = 0
for (const ms of stages) {
total += ms
}
console.log(`${stages.length}:${total}`)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?
const logs = ['info', 'warn', 'error']
const subset = logs.slice(0, 2)
subset.push('debug')
console.log(logs[2], subset[2])Question 12
During a migration, stale feature toggles are removed with splice before adding a guard rail. What array snapshot is logged?
const toggles = ['payments', 'beta', 'legacy', 'audit']
toggles.splice(1, 2, 'guard')
console.log(toggles)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?
const metrics = [3, 5, 8]
metrics.push(13)
if (metrics.length > 3) metrics.pop()
console.log(metrics.length)Question 14
A content pipeline merges two tags lists and needs to know whether the original tag array mutated. What line is printed?
const tags = ['news', 'tech']
const merged = tags.concat(['ai', 'cloud'])
console.log(`${tags.length}:${merged.length}`)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?
const buffer = ['a', 'b', 'c']
buffer.length = 0
buffer.push('d')
console.log(buffer)Question 16
A metrics reporter reads array length inside a loop that shifts processed items. What string appears after processing two samples?
const samples = [10, 20, 30]
let processed = 0
while (samples.length) {
samples.shift()
processed++
if (processed === 2) break
}
console.log(`${processed}:${samples.length}`)Question 17
A documentation generator reverses an array via slice and reverse to keep the original intact. What summary line is printed?
const changelog = ['v1', 'v1.1', 'v1.2']
const reversed = changelog.slice().reverse()
console.log(`${changelog[0]}|${reversed[0]}`)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?
const source = ['init', 'ready']
const combined = [...source, 'error', 'recover']
console.log(source.length === combined.length)Question 19
A diagnostics report tracks which indices were mutated during a cleanup by pairing indexOf lookups with splice. What tuple is logged?
const issues = ['E02', 'E14', 'E07', 'E14']
const first = issues.indexOf('E14')
issues.splice(first, 1)
const second = issues.indexOf('E14')
console.log(`${first}|${second}`)Question 20
A data pipeline flattens the first two nested arrays by concatenating them before computing the resulting length. What number prints?
const batches = [[1, 2], [3, 4], [5]]
const combined = batches[0].concat(batches[1])
console.log(combined.length)Question 21
During rollback analysis, an engineer inspects an array copy constructed with Array.from before pushing a new marker. Which two markers appear?
const releases = ['1.0', '1.1']
const copy = Array.from(releases)
copy.push('rollback')
console.log(releases[1], copy[2])Question 22
An experiment calculates running totals using forEach alongside manual indexing. After the loop completes, what string leaves the console?
const values = [2, 4, 6]
let total = 0
values.forEach((value, index) => {
total += value * (index + 1)
})
console.log(total)Question 23
A refactor introduces Array.isArray checks to guard multi-source inputs. What boolean pair prints?
const maybeList = JSON.parse('[1,2,3]')
const status = [Array.isArray(maybeList), Array.isArray(maybeList[0])]
console.log(status.join(','))Question 24
Support tools frequently remove the first alert after rendering it. With a combination of shift and length arithmetic, what value is logged?
const alerts = ['critical', 'major', 'minor']
const first = alerts.shift()
console.log(`${first}-${alerts.length}`)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?
const sprint = ['Mon: dev', 'Tue: qa', 'Wed: release']
sprint.shift()
sprint.unshift('Plan')
console.log(sprint.join(' | '))Question 26
A backend utility merges multiple arrays and then truncates to a maximum of five items using length manipulation. What string is printed?
const a = ['a1', 'a2']
const b = ['b1', 'b2', 'b3']
const merged = a.concat(b)
merged.length = 5
console.log(merged.join(','))Question 27
A support script repairs a queue by inserting an escalated ticket before the last two items. Which array snapshot is logged?
const queue = ['T1', 'T2', 'T3', 'T4']
queue.splice(queue.length - 2, 0, 'Escalated')
console.log(queue)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?
const rotation = ['north', 'east', 'south', 'west']
const head = rotation.shift()
rotation.push(head)
console.log(rotation[0])Question 29
A devtools extension captures the last two commits only if more than two exist. After slice runs, what JSON snippet appears?
const commits = ['c1', 'c2', 'c3', 'c4']
const subset = commits.length > 2 ? commits.slice(-2) : commits
console.log(JSON.stringify(subset))Question 30
A content pipeline calculates the first index of a marker and the last index using indexOf and lastIndexOf. Which tuple is printed?
const markers = ['start', 'mid', 'mid', 'end']
console.log(`${markers.indexOf('mid')},${markers.lastIndexOf('mid')}`)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?
const stack = []
if (!stack.length) stack.push('bootstrap')
stack.push('deploy')
console.log(stack[0] + '/' + stack.length)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?
const parts = ['npm', 'run', 'build']
const isValid = parts.every(part => typeof part === 'string')
console.log(isValid ? parts.join(' ') : 'INVALID')Question 33
During data normalisation, undefined values are filtered out before the array is stringified. What string prints?
const readings = [undefined, 'ok', undefined, 'warn']
const filtered = readings.filter(Boolean)
console.log(filtered.join('|'))Question 34
A regression test concatenates two arrays and checks whether the original array object reference changed. What boolean prints?
const primary = ['p1', 'p2']
const combined = primary.concat(['p3'])
console.log(primary === combined)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?
const sensors = ['north', 'south', 'east']
sensors.shift()
sensors.unshift('west')
console.log(sensors)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?
const adjustments = ['fee', 'tax', 'discount', 'credit']
adjustments.splice(2, 0, 'placeholder')
const trimmed = adjustments.slice(0, 4)
console.log(trimmed)Question 37
A mobile app caches three most recent searches by pushing and then slicing. After inserting a new term, what string prints?
const searches = ['router', 'switch', 'firewall']
searches.push('access point')
const recent = searches.slice(-3)
console.log(recent.join(', '))Question 38
A data science notebook reads the length difference between two arrays after push and pop operations. What numeric difference shows?
const base = [1, 2, 3]
const test = base.slice()
test.push(4, 5)
test.pop()
console.log(test.length - base.length)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?
const queue = []
queue.push('task-1')
queue.push('task-2')
queue.push('task-3')
while (queue.length > 2) {
queue.shift()
}
console.log(queue)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?
const statements = ['console.log('ready')', 'runTests()']
statements.unshift('import { runTests } from './tests')
statements.push('cleanup()')
statements.pop()
console.log(statements.length)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.
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?
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?
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?
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?
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?
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?
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?
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?
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?
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.
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?
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?
Question 54
When logging array state for debugging, why might JSON.stringify yield clearer results than join?
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?
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?
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?
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?
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?
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?
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?
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?
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?
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?
Question 65
When merging analytics datasets, you must avoid duplicates while keeping order stable. Which array method combination is cleanest?
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?
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?
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?
Question 69
A monitoring script empties an array by setting length = 0 before pushing new entries. Why should you document this behaviour?
Question 70
You evaluate code that pushes values into an array inside setInterval without ever removing them. What long-term issue should you flag?
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?
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?
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?
Question 74
A lead engineer warns that using splice within a forEach callback can lead to confusing results. Why?
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?
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?
Question 77
Why might you prefer to accumulate results with reduce when computing grouped statistics from an array of records?
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?
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?
Question 80
Why is it important to avoid mutating the array passed into a React component via props when preparing derived state?
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?
Question 82
When would you favour using Array.from over spread syntax to create an array from an iterable?
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?
Question 84
Why might you choose splice over slice when building an undo stack for destructive operations?
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?
Question 86
When would using findIndex be more expressive than indexOf?
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?
Question 88
Why might you prefer to use destructuring assignment `const [first, ...rest] = array` in place of manually shifting the first element?
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?
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?
Question 91
Why should you avoid using delete array[index] when removing elements?
Question 92
A script repeatedly calls unshift on large arrays to add history entries. Which alternative reduces the cost of reindexing all elements?
Question 93
When computing moving averages, why might you precompute prefix sums rather than repeatedly calling slice and reduce?
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?
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?
Question 96
A data import pipeline must guarantee stable order but also deduplicate entries. What pattern achieves both goals?
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?
Question 98
Why is it beneficial to define array operations in small helper functions (e.g., addItem(list, item)) when collaborating in large teams?
Question 99
A security scanner must compare two arrays of permissions for equality. Why is comparing JSON.stringify outputs risky?
Question 100
When constructing long-running queues, why is it safer to copy arrays before handing them to third-party libraries?
