ppecher
ppecher

Reputation: 1988

Immutable primitive types

Why can't the following argument be made against the claim that primitive types are immutable in Javascript:

var $b = false;
$b = true;
alert($b); //-> true

I am misunderstanding what it means for a variable to immutable.

Upvotes: 2

Views: 1091

Answers (3)

Scope is mutable, true and false are not. You just showed that scope is mutable, and nothing about whether or not true or false are mutable.

Upvotes: 0

simshaun
simshaun

Reputation: 21466

An immutable variable is one that can't be changed, like a constant. Unfortunately, there are no true immutable variables in JavaScript (at least that I am aware of).

The closest you can get is by using a closure with a getter method.

Upvotes: 0

SLaks
SLaks

Reputation: 887479

Values are immutable; variables are not.

$b = true changes $b to contain the true value.
The immutable false value is not changed.

Some languages support immutable variables as well (C++'s const, Java's final, or C#'s readonly); Javascript does not.

Upvotes: 11

Related Questions