13. Implement classNames() — The clsx Utility

easy

Every React codebase uses classnames or clsx. Rebuilding it shows you can handle a polymorphic argument list cleanly.

The idea

Each argument can be one of several shapes. Branch by type:

  • string / number → include as-is.
  • array → recurse (supports nesting).
  • object → include each key whose value is truthy — the conditional-class pattern.

Falsy arguments (false, 0, '', null, undefined) are silently dropped, which is what makes classNames('btn', isActive && 'active') read so well.

Follow-ups

  • "Why not .filter(Boolean).join(' ')?" → that misses the object and array forms that make the API useful.
  • "Dedupe classes?" → wrap the result in a Set if asked, noting the perf cost.

What to practice

Implement it, then handle deeply nested arrays of objects in one pass.

More questions

index.js
function classNames(...args) {
  // your code here
}

console.log(classNames('btn', { active: true, disabled: false }, ['lg', 'rounded']));
// "btn active lg rounded"

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.