Do variables need to be declared if they're being used in a function?

I’m doing the FCC lesson “Global Scope and Functions”. It uses a variable oopsGlobal in the function. But it doesn’t seem to me that the variable is declared anywhere, I only see it being defined. Do you need to declare a variable? Thanks

// Declare your variable here
var 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);
}

Not sure if I answered your question in the other thread.

I’d suggest giving this a good read.
You Don’t Know JS Yet: Scope & Closures - 2nd Edition

1 Like

@lasjorg Yes I think you mostly did answer it, thanks. I also didn’t realize that you could declare a variable without using var, let, or const (or maybe others one I don’t know about). My point is, I thought code like oopsGlobal = 5; or inGlobal = 'I really should not be here wasn’t just a “bad idea” because it ends up in the global scope, but functionally incomplete and would cause an error.

I thought it wasn’t declaring a variable and trying instead to go straight to defining it, and would not work. Ok I will check out that link, thank you!

It is pretty much for historical reasons that it works without declaring. It was to make it more user-friendly so an inexperienced programmer that forgot to declare the variable would be “helped” by the language. It turns out to be a really bad idea and something that should never have been implemented.

If JavaScript was invented today with the standards body in place and no baggage, it would not let you assign values to undeclared identifiers. The ‘use strict’ directive (strict mode) can be seen as a backward-compatible way of fixing this implementation mistake.

2 Likes