Learn Variable Scopes In JavaScript


Hey Everyone,
Welcome to this blog,
I am Aryan Sharma and this blog is part of the JavaScript Course.
What is variable scope?
Scope tells us about the visibility and accessibility of a variable. JavaScript has three scopes:
The global scope
Local scope
Block scope (ES6)
Global scope: Variables defined globally (i.e. not inside a block or function) are part of the global scope and can be accessed from anywhere in the code. When declared in the global scope, var
, let
and const
behave the same in terms of scope.
var surname = 'Sharma';
The variable surname
is global-scoped. It can be accessed anywhere in the script.
Local scope: Variables defined inside a block or function can only be accessed from the block or function where they were defined, as well as nested local scopes.
When declared inside a block scope, var
will be available but undefined
in outer scopes, while let
and const
will not exist in outer scopes.
var surname = 'Sharma';
function name() {
var surname = 'Kumar';
console.log(surname);
}
name();
console.log(surname);
Output-
Kumar
Sharma
When the JavaScript engine executes the name()
function, it creates a function execution context.
And when the variable surname
declared inside the name()
function is bound to the function execution context of the function, not the global execution context.
TASK:
Have a look at this carefully and try to understand it.
Thanks for reading🙏🏼
Have an awesome learning and Coding day my friend💖
Subscribe to my newsletter
Read articles from aryan sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

aryan sharma
aryan sharma
Hey, Awesome ones! Aryan this side👋 Full-Stack Developer, Life-Long Learner, Optimistic Using this blog to help code newbies. Learn with me! :)