+ 2
Why this code gives an error?
6 ответов
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.
+ 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)
+ 2
Mirielle okay thanks but why didn't it work? Because x is 3 in the function scope
+ 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 ?
- 1
Let x=2;
Let y=x;
Function foo(y,x)....