Scope of Variables

This lesson gives details on scope of a variable and the difference between value and reference types.

Scope of a variable #

A variable of any type is only known in a certain range of a program, called its scope. In a programming language, there are two main types of scopes:

  • Global scope
  • Local scope

Global scope #

The scope of the variables declared outside of any function (in other words at the top level) is called global scope. Global scope is also known as package scope because the variables with such scope are visible and available in all source files of a package.

Local scope #

The scope of the variables declared inside a function is called local scope. They are only known in that function; the same goes for parameters and return variables of a function.

In simple words, mostly, you can think of a scope as the code block ( surrounded by { } ) in which the variable is declared. Run the following program to visualize the concept of scope.

Get hands-on with 1200+ tech skills courses.