Skip to main content

Constants and Variable Declarations

Constants and variables are declarations that bind a value and type to an identifier. Constants are initialized with a value and cannot be reassigned afterwards. Variables are initialized with a value and can be reassigned later. Declarations can be created in any scope, including the global scope.

Constant means that the identifier's association is constant, not the value itself — the value may still be changed if it is mutable. For example, you can change the values inside of a constant array, but you cannot replace the array assignment with a new array.

Constants are declared using the let keyword. Variables are declared using the var keyword. The keywords are followed by the identifier, an optional type annotation, an equals sign =, and the initial value:


_15
// Declare a constant named `a`.
_15
//
_15
let a = 1
_15
_15
// Invalid: re-assigning to a constant.
_15
//
_15
a = 2
_15
_15
// Declare a variable named `b`.
_15
//
_15
var b = 3
_15
_15
// Assign a new value to the variable named `b`.
_15
//
_15
b = 4

Variables and constants must be initialized:


_10
// Invalid: the constant has no initial value.
_10
//
_10
let a

The names of the variable or constant declarations in each scope must be unique. Declaring another variable or constant with a name that is already declared in the current scope is invalid, regardless of kind or type:


_23
// Declare a constant named `a`.
_23
//
_23
let a = 1
_23
_23
// Invalid: cannot re-declare a constant with name `a`,
_23
// as it is already used in this scope.
_23
//
_23
let a = 2
_23
_23
// Declare a variable named `b`.
_23
//
_23
var b = 3
_23
_23
// Invalid: cannot re-declare a variable with name `b`,
_23
// as it is already used in this scope.
_23
//
_23
var b = 4
_23
_23
// Invalid: cannot declare a variable with the name `a`,
_23
// as it is already used in this scope,
_23
// and it is declared as a constant.
_23
//
_23
var a = 5

However, variables can be redeclared in sub-scopes:


_13
// Declare a constant named `a`.
_13
//
_13
let a = 1
_13
_13
if true {
_13
// Declare a constant with the same name `a`.
_13
// This is valid because it is in a sub-scope.
_13
// This variable is not visible to the outer scope.
_13
_13
let a = 2
_13
}
_13
_13
// `a` is `1`

A variable cannot be used as its own initial value:


_10
// Invalid: Use of variable in its own initial value.
_10
let a = a