Scope

Learn about the concept scope and its effect on variables.

Introduction to scope

The concept of a variable’s “scope” is important in any programming language. The scope of a variable or function refers to the parts of the program where they can be accessed. Most languages have some form of lexical scope, which means the scope of a variable is based on where it appears in the code. Often placing a variable inside a block will restrict its scope to that block. A few languages, such as Perl and other Lisp-style languages, use dynamic scope, which means the scope of a variable can change while the program is running.

Global scope covers the entire the program. Any variable or function that can be accessed anywhere in the program is said to have global scope.

Local scope refers to a function or variable that’s only available inside a particular code block. Any function or variable defined inside a block can only be accessed inside that particular block, where they’re “in scope.”

To demonstrate this, let’s try defining some variables. First of all, let's define a variable in the global scope by simply defining it in the main body of the program:

Get hands-on with 1400+ tech skills courses.