Sobes.tech
Junior — Middle

Can you explain the main differences in scope in functions?

sobes.tech AI

Answer from AI

Scope in functions determines where variables and functions are accessible. Main types of scope:

  • Local scope: variables declared inside a function are only accessible within that function.
  • Global scope: variables declared outside functions are accessible everywhere in the program.
  • Block scope (in languages that support it, such as JavaScript with let/const): variables are only accessible within the block of code (e.g., inside if, for).

Example in Kotlin (Android):

fun example() {
    val localVar = 10 // local variable
    if (localVar > 5) {
        val blockVar = 20 // block scope
        println(blockVar) // accessible here
    }
    // println(blockVar) // error: blockVar is not visible here
}

val globalVar = 100 // global variable

fun another() {
    println(globalVar) // accessible here
}

Understanding scope is important for managing variable visibility and lifetime, preventing name conflicts, and memory leaks.