Reputation: 99
I'm new and learning from FreeCodeCamp, their editor runs the code below and displays " ReferenceError: sTr1 is not defined" screenshot here
However, with Visual Studio Code, and even here in stackoverflow, the code executes without a problem (screenshot from VSC).
I am curious why there is a difference. I also expect the error because of what I learned from another language (Java), that it cannot be used unless the variable was declared first.
var str1 = "hi";
sTr1 = "hey";
console.log(sTr1);
Upvotes: 0
Views: 88
Reputation: 56754
Assigning a value to a variable which hasn't been declared creates a global variable with that name automatically in non-strict mode, and throws a ReferenceError
in strict mode.
Please note that ES modules are always in strict mode.
<script type="module">
foo = "foo";
console.log(foo); // ReferenceError: assignment to undeclared variable foo
</script>
<script>
bar = "bar";
console.log(bar); // "bar"
</script>
<script>
"use strict";
baz = "baz";
console.log(baz); // ReferenceError: assignment to undeclared variable baz
</script>
Upvotes: 1