0
Hours
0
Minutes
0
Seconds

How to create a toggle function in JavaScript? | Frontend Problem Solving | JavaScript Interview Question
@Devtools Tech

341

In this question, you need create a function toggle that accepts an array as input and toggles between the values in a cyclic manner.

const animals = ['dog', 'cat', 'elephant', 'tiger', 'lion']; 
const toggled = toggle(animals);

toggled(); // returns dog
toggled(); // returns cat
toggled(); // returns elephant
toggled(); // returns tiger
toggled(); // returns lion
toggled(); // returns dog
...

This question is based on the concept that you might require to build a toggle functionality between two values like on or off in your web-app. A more advanced use-case could be that you need to generate a captcha or a word whenever clicks on a button. You can initialise your code with a list of items and the user would be presented with the next item in the list whenever they click on the button.

Specifications

  1. Input value should be an array with length >= 1.
  2. If input parameter type is not an array then throw a TypeError.
  3. If input array length <= 0 then throw an error.
  4. The toggle function should cycle between the values in clockwise direction.
  5. Your solution should pass all the test cases.

Submission

Please start the timer before starting and finish your solution within 30-45 mins. Share your solution with us on Twitter or LinkedIn.

Loading IDE...