What will be the result of the below program?
function f(input: boolean) {
let a = 100;
if (input) {
let b = a + 1;
}
return b;
}

Understanding Scope in TypeScript

The correct answer to this TypeScript quiz comes down to a fundamental concept of most programming languages: variable scope. The script throws a compilation error for variable 'b'. Why is this the case?

A variable's scope in TypeScript is the part of the program where the variable can be accessed or referenced. There are two types of scopes in TypeScript: global scope and local scope.

The variable 'a' in the function is in the local scope of the entire function 'f'. This is because it's declared at the top of the function, so it's available throughout the function.

The variable 'b', however, is in a different scope. It's declared inside an 'if' statement. Hence, 'b' has block scope. Block scope means that the variable only exists within the block where it is declared, and you can't access it outside that block. This scope applies specifically to 'let' and 'const' variables in TypeScript.

In the provided code, we attempt to return the variable 'b' from the function. But, outside of the 'if' statement where 'b' was declared, 'b' doesn't exist. Hence, TypeScript compiler will throw a compilation error, pointing to the 'return b' line.

Here's an example to further illustrate this:

function f(input: boolean) {
    let a = 100;
    if (input) {
        let a = a + 1;
        console.log(a); // Will print 101 if input is true
    }
    console.log(a); // Will always print 100
}

Always remember to pay special attention to your variable declarations and their scopes while handling TypeScript, or JavaScript, and be aware of block-level constructs (like 'if' statements) creating their local scope. If you want 'b' to be accessible throughout the function, you should declare it at the same scope level as 'a'.

function f(input: boolean) {
    let a = 100;
    let b;
    if (input) {
        b = a + 1;
    }
    return b; // no error now
}

This understanding of scope is a crucial aspect of TypeScript and, indeed, almost any programming language. By grasping this concept, you can write more reliable and effective code.

Do you find this helpful?