Junior — Middle
Could you explain the concept of variable scope in programming?
sobes.tech AI
Answer from AI
Variable scope is the part of a program where a variable is accessible for use.
In programming, variables can have different scopes:
- Local scope — the variable is declared inside a function or block and is only accessible there.
- Global scope — the variable is declared outside functions and is accessible throughout the program.
- Class scope (in object-oriented programming) — class member variables are accessible within the methods of that class.
For example, in Dart (Flutter), a local variable inside a function is not visible outside:
void example() {
int x = 10; // x is only visible inside example
}
// x is not accessible here
Understanding scope helps avoid errors with variable redefinition and manage data lifetime.