Creating variables without var, let, const?

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;
  **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

Challenge: Global Scope and Functions

Link to the challenge:

To my knowledge if you don’t specify var const 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:

console.log("1" + 1);
console.log("1" + [1, 2, 3]);

What do you think the above will log?

1 Like
console.log("1" + 1);

Would this type cast the int 1 to a string to make 11?

console.log("1" + [1, 2, 3]);

This I am not sure, I didn’t think you could add a string to an array without push or shift.

Yes indeed!

I find this one fun. The integer 1 is cast to a string to create "11" and then 2 and 3 are added to the array, giving:

["11", 2, 3]
1 Like
console.log(1 + [1, 2, 3]);

Does this return [2,2,3] then?

I had to check myself on this one. Here we have another oddity and we still get 11, 2, 3
Peculiar I think.

Can we force JavaScript to store something as a specific type?

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.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.