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