Scope is a simple concept, but there are a lot of wrinkles that make it difficult to explain in a forum post. I suggest you read up on it: You Don’t Know JS: Scope & Closures
Basically, scope defines the context in which a value exists. In JavaScript, scope is most often defined by functions - if you define a variable within a function, you can’t access it from outside of the function. Check out question 7
function func() {
var a = ‘hello’;
}
consle.log(a); // a has been defined within the function func().
//Since it has not been defined outside of the function,
//you get a ReferenceError when calling console.log()
This is true so long as you use the var
keyword. The new ES6 keywords, let
and const
, are block scoped. This means they are only defined within the closest curly braces. Often, this is still a function, but it could also be an if
clause, a for
loop, or just some arbitrarily placed curly braces.
function func() {
let a = ‘hello’;
if (true) { let a = ‘goodbye’;} // this definition only exists within the curly braces.
console.log(a); // 'hello'
}
All of these questions are variations on the same theme. Where is the variable defined?