Understanding Variable Scope in JavaScript
In JavaScript, variable scope determines the accessibility of variables within a program. The scope of a variable defines where it can be accessed and where it is visible.
Global Scope: Variables declared outside of any function or block have global scope and can be accessed anywhere in the program.
JAVASCRIPT1// Global variable 2const name = 'John';
Local Scope: Variables declared within a function or block have local scope and can only be accessed within that function or block.
JAVASCRIPT1function greet() { 2 // Local variable 3 const message = 'Hello'; 4 console.log(message + ', ' + name); 5}
When the
greet()
function is called, it can access the global variablename
and the local variablemessage
. However, variables defined within the function or block are not accessible outside.JAVASCRIPT1greet(); // Output: Hello, John 2console.log(name); // Output: John 3console.log(message); // Error: message is not defined
xxxxxxxxxx
23
// In JavaScript, variable scope determines the accessibility of variables within a program.
// The scope of a variable defines where it can be accessed and where it is visible.
// Global Scope
// Variables declared outside of any function or block have global scope and can be accessed anywhere in the program.
// Example:
// Global variable
const name = 'John';
// Local Scope
// Variables declared within a function or block have local scope and can only be accessed within that function or block.
function greet() {
// Local variable
const message = 'Hello';
console.log(message + ', ' + name);
}
greet(); // Output: Hello, John
console.log(name); // Output: John
console.log(message); // Error: message is not defined
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment