-
-
Notifications
You must be signed in to change notification settings - Fork 4
mutable
pannous edited this page Nov 14, 2020
·
8 revisions
There are two kinds of mutability:
- mutable variables can point to different objects during their lifetime.
- mutable objects can change during their lifetime.
x="hello"
x+=" world" # ok, value was mutable
x="bye" # ok, variable was mutable
* immutable variables point to the same object during their lifetime.
* immutable objects stay completely unchanged during their lifetime.
The first variant is called 'let' variable:
let x="hello" x+=" world" # ok, value was mutable x="bye" # error: variable was immutable
Both properties can be combined with the `constant` keyword or with the [[:=]] sigil:
constant x = "hello" x := "hello" # ok redundant redeclaration x+="ok" # error: immutable value x="hi" # error: constant variable
This is near identical to JavaScript's:
`Uncaught SyntaxError: Identifier 'x' has already been declared`
`Uncaught TypeError: Assignment to constant variable.`
With the only difference being:
If the value is identical then it is OK to re-declare a variable.
In JavaScript it is allowed to re-declare variables without let:
let x=1 x=2 # ok let x=2 # error