Imagine there are two rooms, A and B, and you are in room A. Room A is in it and accessible from within it. So you fall under the A scope. However, for room B, you are outside the room and cannot be accessed from inside, so it is not part of the scope.
Similarly, the scope of a variable is the code block or area where the variable can be accessed. A variable’s scope indicates the visibility and accessibility of the variable in different parts of the program. Scope determines which parts of a program can access a variable and where it can be used.
- Global variable:
Variables declared outside of a function are considered global and are accessible throughout the program.