Question:

What does the following code print to the console?

var happy = {
  hi: function sing(n, result) {
    result = typeof result !== 'undefined' ? result : [];
    if (n == 0) {
      result.push("No more bottles");
      return result;
    }
    var str = n + " bottles";
    result.push(str);
    return sing(n - 1, result);
  }
}

console.log(happy.hi(3));

Answer:

["3 bottles", "2 bottles", "1 bottles", "No more bottles"]

The happy object has a hi property that points to the named function sing(). Object values are typically anonymous functions, but they can also be named functions. A named function works well in this example to allow for recursion.


Keywords:

© 2017 QuizBucket.org