Scope

We say a variable is in-scope if you can talk about at any particular point in your code.

How to tell if a variable is in-scope

Assuming your code is properly formatted. In order to be able to talk about a variable (in-scope), it must have already been declared in the program and be indented the same or less as the place where you use it.

This is not a very good formal definition, but it will work in practice.

You can use prettier to format your code perfectly for you.

Examples

const x = 1
console.log(x) // OK since x is defined before and indented the same
console.log(x) // ERROR x hasn't been defined yet!
const x = 1
const x = 1
if (1 > 2) {
  console.log(x) // OK since x is defined before and less indented
}
if (1 > 2) {
  const x = 1
  console.log(x) // OK since x is defined before and indented the same
}
if (1 > 2) {
  const x = 1
}
console.log(x) // ERROR since x is defined before but is indented more.

// x only exists for the length of the if block. Once the if is closed x doesn't exist any more.
if (1 > 2) {
  console.log(x) // ERROR since x is defined lower
} else {
  const x = 2
  console.log(x) // OK since x is defined above and at the same indentation
}
console.log(x) // ERROR since x is defined before but is indented more inside the else.
const double = (x) => {
  console.log(x) // OK since x is a parameter so it's in scope here
}
const double = (x) => {
  console.log(x) // OK since x is a parameter so it's in scope here
}
console.log(x) // ERROR x is only in scope inside the double function
const double = (x) => {
  if (2 > 1) {
    console.log(x) // OK
  }
}
double()
const x = 7
const double = (x) => {
  console.log(x) // OK but which x does this refer to? This is confusing, and a bad idea!
}
double()
const double = (x) => {
  console.log(y) // OK suprise! When this program runs const y = 7 happens is defined before double runs. This is a bad idea!
}
const y = 7
double()
const double = (x) => {
  console.log(y) // ERROR this time double() is called before y is defined - please avoid
}
double()
const y = 7