← JavaScript Coding

Fill

easy

Problem statement

Implement a function fill(array, value, [start=0], [end=array.length]) that fills an array with values from start up to, but not including, end.

Note: This method mutates the original array.

Example

fill([1, 2, 3], 'a'); // ['a', 'a', 'a']
fill([4, 6, 8, 10], '*', 1, 3); // [4, '*', '*', 10]

How to approach Fill

The strategy an interviewer expects you to reach for.

fill mutates a range in-place — the interview is mostly about index normalization, not the loop. Naive move Loop from start to end without handling negatives or clamping. Where it breaks Negative start/end count from the end. Out-of-range values clamp. end defaults to length. You must mutate the same array reference and return it. The fix Normalize start/end exactly like the spec (negative → length+index, clamp). Then assign array[i] = value for i in [start, end). Remember: Normalize indexes first; the write loop is the easy part. Say this in the interview: I'd normalize start and end the way Array.prototype.fill does — including negatives — then mutate that slice in place and return the same array.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingMedium

86. API Retry

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub