Implement classNames() | JavaScript Interview Question
@Yomesh Gupta

Do you see value in our efforts?

Devtools Tech is a free platform for Frontend Engineers. It takes a lot of time, effort, and finanical resources to keep the platform running. If you see any value in our work and would like to support us then you can do using the following options.


In our JSX, we set the className prop to add CSS classes to an element. It can be as simple as the following

<p className="classname1 classname2">
    Devtools Tech

Or conditional

<p className={`${shouldAddClassOne ? 'classname1' : ''}  classname2`}>
    Devtools Tech

and it gets complex based on the use-cases.

To help out in such cases, classnames package is a simple JavaScript utility for conditionally joining classNames together. For example --

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

// Arrays are recursively flattened
var arr = ['b', { c: true, d: false }];
classNames('a', arr); // => 'a b c'

In this question, you need to implement the function classNames from scratch. Your function should be able to take different types of inputs and return a valid string of classes.

Loading IDE...