JavaScript Interview Questions
JavaScript
Web DevelopmentFrontendBackendQuestion 19
What is the scope of a variable in JavaScript?
Answer:
The scope of a variable in JavaScript determines where the variable is accessible within the code. There are two main types of scope: global and local. Global variables are declared outside of any function and are accessible throughout the entire script, whereas local variables are declared within a function and are only accessible within that function. Understanding variable scope is crucial for managing data and avoiding conflicts in your code.
Here is an example demonstrating global and local scope:
var globalVar = 'I am a global variable';
function myFunction() {
var localVar = 'I am a local variable';
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}
console.log(globalVar); // Accessible
console.log(localVar); // Uncaught ReferenceError: localVar is not defined
myFunction();
In this example, globalVar
is accessible both inside and outside the function myFunction
, while localVar
is only accessible within myFunction
.