3

I've created a Javascript function which takes a variable number of arguments and prints each out on a new line:

var printOut = function () {
    for (var i = 0; i < arguments.length; i++) {
        document.writeln(arguments[i] + '<br>');
    }
};

printOut('a', 'b', 'c');
printOut('d', 'e');

The function prints out:

a
b
c
d
e

What I'd like to know is whether it's possible to take this function and make it recursive, but the output is in the same order? From what I've studied, recursion would reverse the order of the output no?

Fiddle: https://jsfiddle.net/klems/kao9bh6v/

3
  • Can you give an example of how you'd like to use the recursive function? Would you still call printOut('a', 'b', 'c') then printOut('d', 'e') ? Commented Mar 8, 2017 at 15:57
  • I'd like to call printOut('a', 'b') first of all Commented Mar 8, 2017 at 15:59
  • To be frank—What's the point? Commented Mar 8, 2017 at 16:01

1 Answer 1

3

You could slice the arguments and call the function again with apply.

var printOut = function () {
    if (arguments.length) {
        console.log(arguments[0]);
        printOut.apply(null, [].slice.call(arguments, 1));
    }
};

printOut('a', 'b', 'c');
printOut('d', 'e');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.