Could someone help me? (again) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Could someone help me? (again)

/*I need help again!*/ window.onload = hello(); function hello() { var x = 192; hithere(); } function hithere() { document.write(x); } /*It says "Uncaught TypeError: 'x' is not defined." What did I do wrong this time?*/

11th Dec 2018, 11:39 AM
Ibaadi Jaya
Ibaadi Jaya - avatar
4 Answers
+ 8
x is defined only inside the function hello(), it has no existence in hithere(). There are many ways to fix it, depending on what you need. One simple option is to just put the "var x=192;" part inside hithere(). But let me know if you want to achieve something else. P.S. Don't worry, you're doing just fine! We've all made these mistakes at some point. Have fun! 😊
11th Dec 2018, 11:43 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
Hello as Kishalaya Saha already explained, you are defining the variable x only inside the hello() function so it can be used only inside it, if you want to use it outside of it you should put the var x outside the function so you can use it everywhere! Or if you want to pass the variable x from hello() to hithere() you should do like this: function hello(){ var x = 192; hithere(x); } function hithere(x){ document.write(x) } But I suggest you to read the function topic in the javascript course to get a better understanding of how to pass variables 😊 Hope it helps anyway!
11th Dec 2018, 11:54 AM
Sekiro
Sekiro - avatar
+ 4
Thanks Sekiro, I was just going to write that! 😊 Passing x as an argument of the function hithere() is the safest way. Writing "var x=192;" before defining the function hello() also works, as that makes x a global variable, accessible anywhere after it is defined. Another option is to write just "x = 192;" (without the var part) inside the hello() function. That automatically makes x a global variable, and then you can access it from hithere() without passing it as an argument. But I won't recommend this method, as when your code gets big, it becomes hard to keep track of these things, and that leads to bugs. Reference: https://www.w3schools.com/js/js_scope.asp
11th Dec 2018, 12:10 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
Kishalaya Saha Is there a way for me to get the value from x inside hello() into hithere()?
11th Dec 2018, 11:47 AM
Ibaadi Jaya
Ibaadi Jaya - avatar