Why this code gives an error? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
3rd Feb 2021, 4:12 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
5 Answers
0
visph Apongpoh Gilbert Mirielle visph yeah thanks guys. I wanted to know the reason for the error. I just found the answer online after an hour or two of searching. It's a problem with hoisting and TDZ(Temporal Dead Zone). Variable declarations are hoisted including let and const but as opposed to var, they are not assigned undefined during the creation phase unless declared at the top of the scope. Their values are unreachable (that's TDZ). Function parameters are in a different scope called intermediate scope and y has to first look for the value of b in the intermediate scope. Here lies the case where b is in the intermediate scope and has been hoisted but it's value is unreachable (TDZ). That's why it's gives that error. Thanks anyway 😊. I'm glad I've understood.
3rd Feb 2021, 6:46 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 4
ReferenceError: Cannot access 'x' before initialization The console is given you the answer already.It's there to help you fixed bugs too. foo(x, y=x)
3rd Feb 2021, 4:39 PM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
+ 2
Mirielle okay thanks but why didn't it work? Because x is 3 in the function scope
3rd Feb 2021, 4:30 PM
جوردن آهو ماولی
جوردن آهو ماولی - avatar
+ 1
as soon as you enter in the argument scope (wrapping the function scope), all provided arguments are implicitly declared, so no: the global x value is not in scope of your function arguments ^^ anyway, you didn't use y in your function, so why would you try to assign it with global x value :o ?
3rd Feb 2021, 5:46 PM
visph
visph - avatar
- 1
Let x=2; Let y=x; Function foo(y,x)....
4th Feb 2021, 8:07 PM
Muhammadoufi
Muhammadoufi - avatar