0
var a = "happy";
// -> undefined

This is code from the console. Why when we declare anything like var a = "happy" in the console after clicking the enter the next line , why it showing undefined?

What is happing in the console?

  • 2
    The console is outputting the response from the command you entered in to it. Declaring a variable has no response, so you see `undefined`. – Rory McCrossan May 08 '23 at 15:12

1 Answers1

1

That is because the operation doesn't return anything. It simply stores a value in a variable and doesn't compute a result to display in the console. This is very similar to a call to a function with an empty return statement or no return statement at all. In order to access the stored value, you will need a second line simply saying a;. Beside, the use of var is now deprecated and I would advise using let instead.