Pages

Saturday, 6 January 2024

block scope VS function scope

 

0 TLDR;

Simply put, a block scope is a subscope of its enclosing function scope.
In below C code, "x" is a function scoped variable, while "y" is a block scoped variable.


int main(){
    int x = 0;    // x is function scoped variable
    if(1==1){    
        int y = 0; // y is block scoped variable
    }
}

1 Python doesn't have block scopes

Most popular programming languages support block scopes, such as C, C++, Java, Golang.
Some languages don't support block scopes. Python is one of them.

def main():
    x = 0        // x is function scoped
    if True:
        x = 10    // this x is also function scoped (same as above x)
    print(x)

The two "x" refer to the same variable.
The output will be "10".

2 JavaScript is crazy about scopes

Block scopes was not supported in early versions of JavaScript. e.g.

function myf(){
    var x = 0        // this x is function scoped
    if(true){
        var x = 10    // this x is the same as above x
    }
    console.log(x);    // this x refer to function scoped x
}
myf()

The output will be "10".

But later, two keywords, "let" and "const", were added to support block scope. By simply replacing "var" with "let", the above code will be block scoped.

function myf(){
    let x = 0        // this x is function scoped
    if(true){
        let x = 10   // this x is block scoped
    }
    console.log(x);  // this x refer to function scoped x
}
myf()

The output will be "0" this time.


No comments:

Post a Comment