What is a scope anyway?
Fortunately defining what scope isn't super complicated to explain. A scope just refers to how variables can be seen or accessed from within your code/program.
Scopes in JavaScript have three levels:
- Global
- Local
- Block
1. Global Scope
All variables that are declared outside of functions are considered to have a global scope. This means they can be accessed anywhere by all functions within your program.
2. Local Scope
If a variable is declared within a function then that variable is considered to have a local scope. That variable only exists within that function and only sub-functions have access to it.
Let's take a look at some examples:
var myName = "Sheldon";
console.log(myName);
Since myName is a global variable this should work just fine and print "Sheldon" on the console.
Let's look at another one:
function printMiddleName(){
var middleName = "Lee";
}
console.log(middleName)
Now if you tried running this piece of code you would run into an error: "Uncaught ReferenceError: middleName is not defined". Because middleName is defined inside a function we have to ask the function to print out or return the name for us like this:
function printMiddleName(){
var middleName = "Lee";
return middleName;
}
console.log(printMiddleName());
And this piece of code should run just fine.
Just keep in mind if you had nested functions (A function inside a function) and you tried accessing a variable from within a sub-function you would get that same error from before.
var myName = "Sheldon"
function printMiddleName(){
var middleName = "Lee";
function printLastName(){
var lastName = "Cooper";
}
console.log(myName,middleName,lastName)
}
printMiddleName()
This code above just wouldn't work because we're trying to access a local variable where it doesn't exist.
var myName = "Sheldon"
function printMiddleName(){
var middleName = "Lee";
function printLastName(){
var lastName = "Cooper";
return lastName
}
console.log(myName,middleName,printLastName())
}
printMiddleName()
This should work fine and print out "Sheldon Lee Cooper".
3. Block Scope
The block is pretty new and wasn't really a thing until ES6 (2015). Variables declared within curly brackets get the block scope. The only keywords that can have a block scope are the let and const.
{
var name = "Sheldon";
let middleName = "Lee";
const lastName = "Cooper";
}
console.log(name); β //this will print out "Sheldon"
console.log(middleName);β //will throw an error
console.log(lastName); β //will also throw an error
Variables with a block scope can't be accessed outside their block.
Conclusion
I hope you liked and found this blog useful. If there is any missing or inaccurate information I would really appreciate your feedback. Thanks for reading till the end.
Top comments (0)