0

What is the difference between the following two cases:

CASE 1:

console.log(c); //console : undefined
var c;

CASE 2:

console.log(c); //console : Uncaught ReferenceError: c is not defined

Why in Case 1 it console undefined? as it was declare after console.log(). At that time variable c is also not defined than why program console undefined

Faraz Babakhel
  • 654
  • 5
  • 14
  • 4
    it has to do with *hoisting* - https://developer.mozilla.org/en-US/docs/Glossary/Hoisting - i,e technically, your first code snippet is equivalent to .. `var c; console.log(c);` -because variable declarations are hoisted to the top of the function scope – Jaromanda X Sep 08 '18 at 03:36
  • 1
    interestingly the output is identical with `console.log(c); var c = 'hello, world';` ... because then the code is equivalent to `var c; console.log(c); c = 'hello, world';` - which demonstrates "hoisting" a little more clearly – Jaromanda X Sep 08 '18 at 03:38
  • 1
    [What went wrong?](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined) There is a non-existent variable referenced somewhere. This variable needs to be declared, or you need make sure it is available in your current script or scope. – Bhojendra Rauniyar Sep 08 '18 at 03:48

1 Answers1

1

Please check docs for var statement in MDN

variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

So, in first example variable has been declared, but was not defined (even with var c = 1; before that row it would be not defined). In the second example, it was not declared at all.

extempl
  • 2,987
  • 1
  • 26
  • 38