FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Use Media Query

20mins

Implement a function createMediaQuery(query) that listens to media query changes (e.g. screen size, resolution, orientation) using the window.matchMedia API.

The function should:

  • Accept a valid CSS media query string.
  • Return an object containing:
    • matches: boolean (whether the media query currently matches).
    • subscribe(callback): function that registers a listener to be notified whenever the match state changes.
    • unsubscribe(callback): function that removes a previously registered listener.

Example

const media = createMediaQuery('only screen and (max-width: 768px)'); console.log(media.matches); // true/false depending on viewport function handler(matches) { console.log('Media query changed:', matches); } media.subscribe(handler); // Later, to stop listening media.unsubscribe(handler);

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests