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.

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.

1
// Declare a constant named `a`.
2
//
3
let a = 1
4
5
// Invalid: re-assigning to a constant.
6
//
7
a = 2
8
9
// Declare a variable named `b`.
10
//
11
var b = 3
12
13
// Assign a new value to the variable named `b`.
14
//
15
b = 4

Variables and constants must be initialized.

1
// Invalid: the constant has no initial value.
2
//
3
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.

1
// Declare a constant named `a`.
2
//
3
let a = 1
4
5
// Invalid: cannot re-declare a constant with name `a`,
6
// as it is already used in this scope.
7
//
8
let a = 2
9
10
// Declare a variable named `b`.
11
//
12
var b = 3
13
14
// Invalid: cannot re-declare a variable with name `b`,
15
// as it is already used in this scope.
16
//
17
var b = 4
18
19
// Invalid: cannot declare a variable with the name `a`,
20
// as it is already used in this scope,
21
// and it is declared as a constant.
22
//
23
var a = 5

However, variables can be redeclared in sub-scopes.

1
// Declare a constant named `a`.
2
//
3
let a = 1
4
5
if true {
6
// Declare a constant with the same name `a`.
7
// This is valid because it is in a sub-scope.
8
// This variable is not visible to the outer scope.
9
10
let a = 2
11
}
12
13
// `a` is `1`

A variable cannot be used as its own initial value.

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