So I'm learning about asynchronous programming through callbacks and wrote this code that calculates the next number in a Fibonacci sequence, when I then had trouble setting the value of an HTML element with innerHTML. The text simply would not show up on the screen even though I thought I did everything right. This is the code here that doesn't work:
window.onload = function(){
const print = (fibSeq) =>{
let text = document.getElementById('text').innerHTML
text = fibSeq
}
const calcFib =(callback)=>{
let seq = [0,1]
seq.push(seq[seq.length-1] + seq[seq.length-2])
callback(seq)
}
calcFib(print)
}
I was confused, but then I started tweaking it and found if I just moved innerHTML down one line, the code worked. The code below shows the change, but I don't understand why the code above doesn't work when this one does.
The 'text' variable is set to the element Id and the innerHTML in both examples, yet it only works in one of them. Does anyone understand why? I don't want to move past this without understanding how exactly it was fixed.
window.onload = function(){
const print = (fibSeq) =>{
let text = document.getElementById('text')
text.innerHTML = fibSeq
}
const calcFib =(callback)=>{
let seq = [0,1]
seq.push(seq[seq.length-1] + seq[seq.length-2])
callback(seq)
}
calcFib(print)
}