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.

Navid
  • 45
  • 6
  • 8
    `let a = Array, b;` declares two variables `a` and `b` and initializes `a` with the value `Array`. `let a = b;` declares only one variable `a` and reads undeclared `b`. _"what does Array do in this Javascript function?"_ nothing. – jabaa Apr 14 '23 at 23:23
  • and [What does variable declaration with multiple comma separated values mean (e.g. var a = b,c,d;)](https://stackoverflow.com/questions/11076750/what-does-variable-declaration-with-multiple-comma-separated-values-mean-e-g-v) or [javascript multiple variable assignment in one line](https://stackoverflow.com/questions/49984471/javascript-multiple-variable-assignment-in-one-line) – pilchard Apr 14 '23 at 23:40

2 Answers2

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())
Bergur
  • 3,962
  • 12
  • 20
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;.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80