0

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

2 Answers 2

4

The code:

let a = Array, b;

Is same as

let a = Array;
let b;

Which is the same as

let a = Array;
let b = undefined;

So in the original code you define a as an array and b as an undefined variable. Then a value of 1 is assigned the the variable b, and the variable is the returned. The variable a is never used.

In your code, when you do

  let a = b

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

function Pract() {
    let b = 1
    return b;
}
console.log(Pract())
Sign up to request clarification or add additional context in comments.

Comments

2

let a = Array, b; declares two variables, a and b, and sets the value of a equal to the Array function (b is left with a value of undefined). There are no issues with this and it doesn't really have anything to do with Array. You could set a to any other value, or not set it at all, like let a, b;

However, let a = b; declares only a and attempts to set its value to the value of b, which has not been defined anywhere. Thus there is a ReferenceError. This would work, though, if you put b = 1 before let a = b;.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.