In JavaScript, variables are declared using the 'var' keyword, similar to how data types are declared in languages like Java and C. However, understanding variable scope can be a bit tricky.
Scope refers to the accessibility and visibility of a variable within a specific part of the code. In the case of functions, the scope of a variable is determined by where the function is defined, not where it is invoked. Let's explore an example to gain more clarity:
var a = 5;
var b = 10;
function test3() {
console.log(b); // Scope: Global
}
function test() {
console.log(a); // Scope: Global
var b = 3;
console.log(b); // Scope: Local to the 'test' function
console.log(c); // Hoisting (resulting in 'undefined')
var c = 15;
function test2() {
test3(); // Invoking 'test3' function
console.log(c); // Scope: Enclosed in 'test' function (resulting in 15)
console.log(b); // Scope: Enclosed in 'test' function (resulting in 3)
console.log(a); // Scope: Enclosed in 'test' function and then Global (resulting in 5)
}
test2(); // Invoking 'test2' function
}
test(); // Invoking 'test' function
test3(); // Invoking 'test3' function
/**
// Output
5
3
undefined
10
15
3
5
10
**/
Now, let's highlight some key points from the example:
Direct Invocation: We can directly call the functions 'test' and 'test3.' However, to call 'test2,' it needs to be returned from the 'test' function and then invoked using the returned value.
Variable Declaration and Scope: Variables 'a' and 'b' are declared in the global scope, making them accessible throughout the code.
Local Variable 'b': Inside the 'test' function, there's a local variable 'b' with a value of 3. This local variable 'b' does not affect the value of the global 'b.'
Scope Chaining: When the function 'test3' is invoked, it looks for the variable 'b' first within its own scope (which is global) and then in the global scope.
Variable 'a' in 'test2': The 'test2' function does not have its own 'a' variable. When it tries to access 'a,' the scope chain goes up until it finds 'a' in the global scope, resulting in 'undefined.'
Hoisting of 'c': The variable 'c' is hoisted to the top of the 'test' function, so it exists within the function but is not initialized yet when accessed before its declaration, leading to 'undefined.'