-1

enter image description here

why javascript var shows undefined instead of giving an error message when we use var/function before declaring? In the end when I tried printing the value of x why it is printing both values of x and undefined. Can anyone please clarify this? I tried searching on the internet but was not able to find any answer.

  • What is the reason it should give an error? – VLAZ May 28 '22 at 18:39
  • I suggest you go through MDN docs. Here's an excerpt "undefined is a property of the global object. That is, it is a variable in global scope. The initial value of undefined is the primitive value undefined. A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned." - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined – Hackinet May 28 '22 at 18:40
  • It logs twice because the console always prints the result of the expression you run, so the logging of the value is what `console.log` does and undefined is logged because `console.log` doesn't *return* anything and thus the result of the expression is `undefined`. – Lennholm May 28 '22 at 18:58

0 Answers0