skip to Main Content

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


  1. 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;.

    Login or Signup to reply.
  2. 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())
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search