0

Why does function two not work? I don't understand why the first function works, but not the second.

window.addEventListener("load", () => {
  one();
})
const one = () =>{
  document.querySelector(".fun1").innerHTML = "function one";
}

window.addEventListener("load", two);
const two = () =>{
  document.querySelector(".fun2").innerHTML = "function two";
}
<p class="fun1"></p>
<p class="fun2"></p>
disinfor
  • 10,865
  • 2
  • 33
  • 44
  • 3
    The error message in the console tells you why. Did you not bother to check before asking, or do you have trouble understanding what it means ...? – CBroe Jul 05 '22 at 14:14
  • 2
    He meant in opposition to the first one. and the reason being that on the first one you don't access variable `one` right away. – IT goldman Jul 05 '22 at 14:14
  • i have trouble to understand what is means – code newbie Jul 05 '22 at 14:16
  • 6
    In the first version you look up the name `one` when the listener function is called, which is after it's defined. In the second version you look up the name `two` when calling `addEventListener()`, before you've defined the function. – Barmar Jul 05 '22 at 14:16

1 Answers1

2

Javascript runs top down, so when the first event listener is set it uses an anonymous function, and the important part is the function is not called until the event is triggered.

// this is the anonymous function
() => { 
  one(); 
} 

when your second event listener is hit, it uses a variable that is defined on the following line so its not in memory yet.

Simple solution would be to move the definition of two above the event listener, or wrap it in an anonymous function like you did in the first example.

J D
  • 166
  • 1
  • 13
  • 1
    This isn't exactly true, because hoisting exists. `const` variables are also hoisted, but have an additional mechanism that prevents them from being accessed before initialization. – Konrad Jul 05 '22 at 14:56
  • This is a good point @KonradLinkowski – J D Jul 05 '22 at 15:47