Tell us what’s happening:
I don’t understand how oopsGlobal can be declared as a variable in this function as it doesn’t have var, let, or const before it to identify it as a variable? It’s just numbers assigned to an undeclared variable. How does JavaScript know it is a variable? Also, while we are on the subject, how can JavaScript know the data type of any variable if we aren’t declaring them as int, string, bool etc… In C I know you need to first define the variable type before you can assign it a value.
Thanks for your time!
**Your code so far**
// Declare the myGlobal variable below this line
let myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5;
}
// Only change code above this line
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36
To my knowledge if you don’t specify varconst or let, JS declares the name as a global variable.
As for no type declaration, that’s the benefit of a high level language. Behind the scenes the language takes care handling pointers and variables types so we can assign a wider range of values to a variable. This can of course have drawbacks for example not knowing what a type is. This can lead to some interesting behavior:
There are ways to convert values in JS, but the only way to force it would probably to use typescript instead. I’ve not used it personally but my simple understanding is it is a “strictly typed JS”
Here’s an interesting point (you may already know).
Though we define a type, the only difference in C types is really the size, all are stored as just basic integers. So what differs? The interpretation of them.