Next up is private scope. Private scope is also known as local scope or function scope. Private scope is achieved by using the var keyword inside of a function. So for example, in this function, I create a variable called speed. And it's private. Because I use the var keyword.
It's that simple. If I use the var keyword inside of a function, that variable that I'm creating becomes private to that function. Now, it's important to point out something very, very critical about JavaScript and that's lexical scope. So lexical scope is the way that scope behaves in JavaScript, in that inner functions can see out but outer functions cannot see in. And what I mean specifically is, in this case, we have three functions outer, middle, and inner. And the inner function which is the animals function is nested.
It's nested twice, it's nested inside middle and middles nested inside our So from the inner function, that function has access to the bar and foo variables, because the inner function can see out it can see any variables declared outside of itself. So the inner function has quite a bit of access, it has access to its own private bands variable, it has access to the bar variable, and it has access to the Foo variable. But the opposite is not true. So the outer and middle functions are not able to see in so the outer function has access to its own private foo variable, but it cannot see inside the middle function, it cannot see the the bar variable, and it cannot see the bass variable because it's inside of the inner function. So once again, functions can see out but they cannot see in and that's lexical scope in JavaScript.
And it's really important to understand that because it's the way that scope behaves in JavaScript. And when you declare a variable using the var keyword, that variable becomes private. to that function, and nothing outside of that function has access to that variable but that function can see any variables defined outside of itself.