AniUI Academy
easy+150 XPPractice

Build the cn() class name merger

Every component library ships a version of this — clsx, classnames, the cn() in a shadcn project. You call it with a base class, a conditional object for state, and sometimes an array from a parent, and it hands back one flat string for className.

Implement cn(...args). Each argument may be a string, a number, a plain object, an array (nested to any depth), or a falsy value. Strings are used as written. Numbers are converted with String(n). For a plain object, each key is included when its value is truthy, in the object's own key order. Arrays are walked recursively in order. Falsy values — null, undefined, false, 0, "" and NaN — are skipped everywhere they appear, including inside arrays and as object values.

Return the collected class names joined by a single space, in the exact left-to-right order they were encountered. Duplicates are kept, not removed. There is no leading or trailing space, and when nothing survives you return the empty string "".

What it has to do

  • Accept any number of arguments: strings, numbers, plain objects, and arrays nested to any depth.
  • Include an object's key only when its value is truthy, keeping the object's key order.
  • Skip every falsy value, including 0, "", NaN, false, null and undefined.
  • Join with a single space, preserve encounter order, and keep duplicate class names.
  • Return "" when no class names survive.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.