Implement classNames() | JavaScript Interview Question
@Yomesh Gupta

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
</p>

Or conditional

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

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...

https://www.devtools.tech/