1

I don't understand why it throws error

str = 'string'; // str is not defined. Why?
let str = 'string2';

console.log(str);

I thought declaring a variable without a keyword would make it look like a var. But it is not.

Intervalia
  • 10,248
  • 2
  • 30
  • 60
Vladimir Mironov
  • 185
  • 1
  • 1
  • 9
  • How does the JS interpreter behave when a variable Declaration occurs without a keyword? Why do I get this error? – Vladimir Mironov May 28 '19 at 16:07
  • 1
    The actual error I see (in FireFox) is "*`ReferenceError`: can't access lexical declaration `str` before initialization*" This should indicate the actual problem is the `let` within the same block, and indeed if you remove the `let str =` it works fine. – p.s.w.g May 28 '19 at 16:07
  • Put that `let` on the first line instead of the second line, or just simply get rid of it. – goodvibration May 28 '19 at 16:08
  • you cannot access 'str' before initialization – TheUnKnown May 28 '19 at 16:08
  • You should first declare the variable `var str;` – Adam Buchanan Smith May 28 '19 at 16:09
  • @goodvibration I know what this working. Bit I don't understand why I get error – Vladimir Mironov May 28 '19 at 16:10
  • javascript doesn't allow implicit variable declarations – Plastic May 28 '19 at 16:11
  • You're confusing the interpreter, that why it's not working. – goodvibration May 28 '19 at 16:12
  • @Plastic it absolutely does. See [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#Description): "*Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.*" Modern coding standards recommend using strict mode which forbids this, but this is something you need to opt in to. – p.s.w.g May 28 '19 at 16:13
  • @p.s.w.g you are absolutely right. it's just forbidden in strict mode – Plastic May 28 '19 at 16:16

1 Answers1

2

You need to declare the variable first, then use it, that's how let works. If you were using the var keyword instead it would have worked.

Using let

str = 'string';        // DOES NOT WORK! here it hasn't been declared
let str = 'string2';   // move this line up before the above line

console.log(str);

Using var

str = 'string';        // IT WORKS because of variable hoisting!
var str = 'string2';

console.log(str);

See: What's the difference between using "let" and "var"?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80