Function Scope in JavaScript

Variables defined inside a function can not be accessed outside of the function because a variable is defined in the scope of the function.


function foo(){
    let text1 = "This is with let";
    var text2 = "This is with var";
    console.log(text1);
    console.log(text2);
}

console.log(text1); //output: error
console.log(text2); //output: error

function foo1(){
    console.log(text1); //output: error
    console.log(text2); //output: error
}
                    

As you can see from above code, you can not access the text1 and text2 inside the foo but you can not access it outside of the foo since it is defined inside foo.
Since variables are defined inside the function, it doesn't matter if they are definde by var or let. You can not access outside of the function.
It will make difference in block scope. We already had a look in this chapter.


if(true){ //it is just for example
    var text1 = "This is with var";
    let text2 = "This is with let";
}
console.log(text1);
//output: This is with var
console.log(text2);
//output: Uncaught ReferenceError: text2 is not defined
                    

In block, if a variable is declared with var, then it can be accessed outside of the block. And if a variable is declared with let, then it can not be accessed outside of the block. But remember, a block should not be a function.

Conclusion

In this section, you learned about the function scope.
In next section, you will learn about the closure in JavaScript.