Hey all! I've been taking an online development course for a few weeks and have working on JavaScript lately. But I've been struggling with the idea of scope.
Can anyone help me understand what scope of variables is in JavaScript?
Many thanks!
Hey all! I've been taking an online development course for a few weeks and have working on JavaScript lately. But I've been struggling with the idea of scope.
Can anyone help me understand what scope of variables is in JavaScript?
Many thanks!
For further actions, you may consider blocking this person and/or reporting abuse
SevenMentor -
Priback1 -
Christopher Jones -
ujwal195 -
Once suspended, surfindev will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, surfindev will be able to comment and publish posts again.
Once unpublished, all posts by surfindev will become hidden and only accessible to themselves.
If surfindev is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to Gene.
They can still re-publish the post if they are not suspended.
Thanks for keeping CodeNewbie Community 🌱 safe. Here is what you can do to flag surfindev:
Unflagging surfindev will restore default visibility to their posts.
Top comments (2)
I like to think the scope as an "area". An area where a variable exists with a given value.
If someone asks me "what is the scope of a variable?", I imagine they try to ask me "where does this variable exists?"
Take this example.
The area of the code where
color
has the valuerebeccapurple
is the block inside theprocess
function. It doesn't exists anywhere else. In fact, that piece of code will throw aReferenceError
telling youcolor
is not defined.There are different types of scope that people mention a lot:
Global scope: Means the whole program. A variable in the global scope is one that you can access in the whole codebase.
Function scope: Means the body of a function. When someone says "this variable doesn't leave the function scope", they try to tell you the variable doesn't exists outside the function.
Block scope: This I need to show you.
Those curly braces form a
block
, and it has it's own scope. What's interesting is that even thought is not a function, the variablecolor
only exists with the valuehotpink
inside those curly braces.When you think about the scope of a variable, just try to ask yourself "where does this variable exists?"
Ok so a little on this. I am going to ignore
var
for this it's special and for another time.So let's talk about block scope. When I am writing something in a file there is a
global
level outside all functions, once I enter a function I am inside the scope of that function, however it doesn't end there, say I enter a statement block likeif (something) { statement block scope }
now comes the interesting part...