JS Interview #4 — What is Scope?
In this blog, we will see Scope in Javascript with the help of examples.
What is Scope?
Scope means availability & duration of availability for Variable. In other words, scope determines the accessibility (visibility) of variables.
JavaScript has 3 types of scope
- Global scope
- Block scope
- Function scope
Global scope
A variable declared at the top of a program or outside a function is considered a global scope variable.
// program to print a text
let a = "hello";
function greet () {
console.log(a);
}
greet(); // hello
In the above program, variable a is declared at the top of the program and is a global variable. It means the variable a
can be used anywhere in the program.
Variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.
function greet() {
a = "hello"
}
greet();
console.log(a); // hello
In the above program, variable a is a global variable.
Block Scope
A variable declared inside a { } block is considered a block scope variable. it cannot be accessed from outside the block.
A variable declared with let
and const
is considered a block scope variable.
{
let x = 2;
const y = 10;
}
// x & y can NOT be access outside
Function Scope
A variable declared inside a function is considered a function scope variable. It is only accessible within that function and not visible outside.
A variable declared with var
the keyword is considered a function scope variable.
function greet() {
var a = "hello";
console.log(a); // hello
}
greet();
console.log(a); // a is not defined
Nested Scopes and Functions
if (true) {
const foo = "foo";
console.log(foo); // "foo"
if (true) {
const bar = "bar";
console.log(foo); // "foo"
if (true) {
console.log(foo, bar); // "foo bar"
}
}
}
function foo(bar) {
function baz() {
console.log(bar);
}
baz();
}
foo("bar"); // "bar"
Key Points to remember
- It is a good practice to avoid using global variables because the value of a global variable can change in different areas in the program or it can overwrite window variables. It can introduce unknown results in the program.
- If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
- In JavaScript, there is
"strict mode"
in which a variable cannot be used without declaring it. - Function arguments (parameters) work as local variables inside functions.
- Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
- Function (local)/Block variables are deleted when the function/block is completed.
- Variables declared with
var
keywords are hoisted butlet
&const
variables declared are not hoisted. - In JavaScript, objects and functions are also variables.
To understand in a much better way here is the video link