Skip to the solution
MediumFrontendAsked in 20246 min read

Query String Generator

1.5k views

The problem

Problem, as an interviewer would state it: "Write toQueryString(obj) — convert a plain object into a URL query string, correctly percent-encoding values, handling array values as repeated keys, and skipping null/undefined."

Examples:

Code
toQueryString({ search: "hello world", tags: ["js", "react"], page: 2 });
// "search=hello%20world&tags=js&tags=react&page=2"

Clarifying questions expected:

  • Should array values become repeated key=val pairs, or a single comma-joined value?
  • Should null/undefined values be skipped entirely, or included as an empty string?
  • Does the key itself ever need encoding too, not just the value?

Code / implementation expected: Yes — real, direct proof handling a string with a space, an array value, a number, and an undefined field, verified against real encodeURIComponent output.

  • object
  • string

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: toQueryString() correctly percent-encodes a space, fans out an array into repeated keys, and skips an undefined field

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 76 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Custom String.prototype.trim polyfill

Continue