Junior — Middle
Can you name types of variables according to their scope in code?
sobes.tech AI
Answer from AI
Variables can be classified by scope:
- Global variables — accessible throughout the entire program, usually declared outside functions and classes.
- Local variables — declared inside functions or blocks and accessible only within them.
- Block variables — in languages with block scope (e.g., JavaScript with let/const), variables are accessible only within a specific block of code (e.g., inside a loop or conditional statement).
- Static variables — retain their value between function calls but are only visible within the function (e.g., static in C).
Example in JavaScript:
let globalVar = 'global'; // global variable
function example() {
let localVar = 'local'; // local variable
if (true) {
let blockVar = 'block variable';
console.log(blockVar); // accessible here
}
// console.log(blockVar); // error, blockVar is not visible here
}