Joan Joan - 4 months ago 8
Javascript Question

What the array().join() does in the following code?

var object = {
mastermind : "Brain",
henchman: "Pinky",
battleCry: function (noOfBrains) {
return "They are " + this.henchman + " and the" +
Array(noOfBrains + 1).join(" " + this.mastermind);
}
};

var battleCry = object.battleCry(4);


--

Can you explain why array().join() return:


  • Correct: "They are Pinky and the Brain Brain Brain Brain"

  • Incorrect: "They are Pinky and the 5 Brain"


Answer

The array().join() is used to join all the elements of an array together in one string. Optionally, you can specify a delimiter to separate the elements.

In your code, Array(noOfBrains + 1) creates a new array with the given length, in your example 4 + 1 = 5 items, but all those 5 items are empty because your code doesn't assign anything to them. So your code is joining 5 empty strings using " Brain" as delimiter. Essentially, this function is actually a repeater of any string assigned to the mastermind property for as many times as you pass it.