+ 1

Why does the following code gives an error saying p_1 is not defined

https://code.sololearn.com/WbAa2Zr7nr6B/?ref=app

8th Jul 2020, 1:02 PM
Abhay
Abhay - avatar
10 Réponses
+ 1
Abhay Sorry. Did not notice because the code was full of commented out text. It turned out that when you give an id to an element, it is added in JavaScript namespace. So that was why it was accessible. See this https://code.sololearn.com/WiJpHv50Zi1u/?ref=app
8th Jul 2020, 3:28 PM
Ore
Ore - avatar
+ 1
Because the onload event fires after detect is created and variable p_1 can not be accessed outside the function You have to pass p_1 as an argument to the function. Like this window.onload=function(){ var p_1=document.querySelector(".page1"); detect(p_1); }; function detect(page){ .....use 'page' not 'p_1' here }
8th Jul 2020, 1:10 PM
Ore
Ore - avatar
0
CodeShow Hoisting is not the issue here. Even if you convert detect to an arrow function the problem still persists. Variables declared inside functions can not be accessed outside the functions no matter what
8th Jul 2020, 1:23 PM
Ore
Ore - avatar
0
Ore I have this similar code and it works well ? Am i missing something! https://code.sololearn.com/WHGX1dAI1cTm/?ref=app
8th Jul 2020, 2:05 PM
Abhay
Abhay - avatar
0
Abhay In your code, the functions are declared within the event callback itself. So they have access to the variables declared within the callback. Its like this function () { var a = 8; //YES function() { //YES } } //NO The regions labelled YES can access the variable a. Those labelled NO can not.
8th Jul 2020, 2:10 PM
Ore
Ore - avatar
0
Ore but it is like this: function(){ } function1(){ }
8th Jul 2020, 3:25 PM
Abhay
Abhay - avatar
0
Thanks a lot :)
8th Jul 2020, 3:39 PM
Abhay
Abhay - avatar