DEV Community

Muse'
Muse'

Posted on

Javascript Scopes Types .. Simplified!

Just like with many programming languages, there’s fundamental concepts that might seem confusing even though they are essential to mastering the target language. We can all agree that Scope and Scope is one of them.

Hopefully by the end of this blog post, you’ll be able to find it less confusing and you’ll be on your way to writing better, more efficient and cleaner code.

What is Scope?

Scope is the accessibility of variables. It refers to where and which part of your program can your variables be accessed/utilized.

How Many types?

Global Scope, Function Scope and Block Scope

Is Scope even that important?

Yes! And the main benefit is security and preventing changes to our variables through out our code and to also make sure we don’t end up with same variables.

Global Scope:

-> Not inside a function or block {}

-> Can be accessed anywhere.

Alt Text

Local Scope:

-> Variable declared inside a function

-> Only accessed in that function and no where else outside..

Alt Text

Block scope:

-> They can be accessed within the nearest pair of curly braves,
but not outside of it.

-> Unlike var, it doesn’t have that block scope limitation.

Alt Text

*Quick tip:

Scopes can be nested on top of each other..

Alt Text

The let variable that’s a block scope, is inside of the local scope, which is nested inside the global scope.

*Quick tip:

Most modern day browsers support "Strict Mode"
which basically means, undeclared variables are not automatically global.
so if you were to assign a variable without const or var, this would throw an error.

Scopes might seem very confusing at first, but with the more practice and detail you give to how you initially write out your code, the less errors and debugging your code will experience..!

Happy coding!

Top comments (0)