I have the following code:
function arraySum(array) {
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function superIncreasingSequence(length = 7) {
sequence = [getRandomInt(10) + 1];
for (let i = 0; i < length; i++) {
sequenceSum = arraySum(sequence);
sequence.push(sequenceSum + getRandomInt(10));
}
return sequence;
}
function displaySuperIncreasingSequence(length = 7) {
sequence = superIncreasingSequence(length)
document.getElementById("superIncreasingSequenceGeneratorResult").innerText = sequence;
}
const superIncreasingSequenceGeneratorBtn = document.getElementById("superIncreasingSequenceGenerator");
superIncreasingSequenceGeneratorBtn.addEventListener("click", displaySuperIncreasingSequence);
<button id="superIncreasingSequenceGenerator" type="button">Generate Sequence</button>
<div id="superIncreasingSequenceGeneratorResult">""</div>
When I run the function displaySuperIncreasingSequence() in the console, the code runs exactly as expected, displaying the following in the div superIncreasingSequenceGeneratorResult:
4,10,18,32,66,133,272,535
BUT, when I press the button (id="superIncreasingSequenceGenerator") on the webpage, a single number is displayed?
Why does the function run differently depending if it's being executed by a click vs manually called in the console?
The problem is here:
superIncreasingSequenceGeneratorBtn.addEventListener("click", displaySuperIncreasingSequence);
That code tells the browser to call displaySuperIncreasingSequence when the button is clicked, passing it an event object for the click. So displaySuperIncreasingSequence receives that event object as length. When your for loop does the < length check, it's false, because an event object cannot be converted to a number, so that ends up being < NaN, which is always false.
It's important not to use functions as callbacks that aren't designed for where they're being used as a callbacks — in this case, as a DOM event handler.
You can fix it by wrapping it in a function so it doesn't get called with any arguments, so it applies the default for length:
superIncreasingSequenceGeneratorBtn.addEventListener("click", () => { displaySuperIncreasingSequence(); });