Skip to the solution
EasyFrontend6 min read

Implement a Theme Toggle That Persists Choice and Respects prefers-color-scheme

195 views

The problem

Problem, as an interviewer would state it: "Build a light/dark theme toggle. Before the user has ever made a choice, it should default to their operating system's preference. Once they explicitly pick a theme, that choice should persist and win over the system preference on every future visit — until they clear it, at which point it should go back to following the system preference again."

Examples:

Code
// no stored choice, OS prefers dark -> theme is "dark"
// user clicks "light" -> theme is "light", persisted
// page reloads -> theme is STILL "light" (the stored choice, not the OS preference)

Clarifying questions expected:

  • Should the theme also update live if the OS preference changes WHILE the page is open and the user hasn't made an explicit choice yet?
  • Where should the choice persist — localStorage, a cookie (for server-rendered pages to know the theme before first paint), or either is fine?
  • Is "system" itself a selectable third option (explicitly "follow the OS", distinct from "no choice made yet")?

Code / implementation expected: Yes — real, live proof against this session's own actual browser: the real OS-level preference is read correctly, an explicit choice correctly persists and survives a simulated reload, and clearing that choice correctly falls back to the system preference again.

  • css
  • media-query
  • localstorage

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, live-verified proof against this session's actual browser: correctly reads the real OS preference, persists an explicit choice across a simulated reload, and reverts on clear

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 42 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 nextEasy

Implement sleep(ms) and delay with value

Continue