I have seen a bit of code similar to this demonstration purpose function, somewhere:
function Pract() {
let a = Array, b;
b = 1;
return b;
}
console.log(Pract())
// Output: 1
However, when I remove Array from the a variable it shows an error:
// And I know this is because b is not defined, but so does b in let a = Array, b;
function Pract() {
let a = b;
b = 1;
return b;
}
console.log(Pract())
// Output: Error
Thanks in advance.
2
Answers
let a = Array, b;
declares two variables,a
andb
, and sets the value ofa
equal to theArray
function (b
is left with a value ofundefined
). There are no issues with this and it doesn’t really have anything to do withArray
. You could seta
to any other value, or not set it at all, likelet a, b;
However,
let a = b;
declares onlya
and attempts to set its value to the value ofb
, which has not been defined anywhere. Thus there is aReferenceError
. This would work, though, if you putb = 1
beforelet a = b;
.The code:
Is same as
Which is the same as
So in the original code you define
a
as an array andb
as anundefined
variable. Then a value of 1 is assigned the the variableb
, and the variable is the returned. The variablea
is never used.In your code, when you do
You should get "b is not defined" error, since you’re saying
a
should be something that has never been defined.To simplify the code, you can simply do