Delving deeper into Variable assignment.
Definition
In computer programming, variables are used to store information to be referenced and manipulated in a computer program. Their sole purpose is basically to label
and store data
in memory.
You should know that naming variables is known as one of the most difficult tasks in computer programming, so think hard about the names.
Ways of Variable Assignment
There are two known ways of variable assignment namely;
- By Value
- By Reference
By Value
Variables that are assigned a primitive data type are said to contain their values. In JavaScript, for example, there are five primitive data types namely; Number
, String
, Boolean
, undefined
and null
.
Examples
let a = 1;
let b = 'boy';
let c = null;
a
contains 1
, b
contains boy
, c
contains null
.
In languages like Ruby, which don’t really have primitive data types, variable assignment is done by way of referencing non-primitive values.
By Reference
Variables that are assigned a non-primitive value are a given a reference
to that value. That reference points to the object’s location in memory (the object’s memory address if you would).
In Ruby, everything is an object.
1.is_a?(Object) => true
false.is_a?(Object) => true
nil.is_a?(Object) => true
[].is_a?(Object) => true
In JavaScript, the known non-primitive data types are Array
, Function
and Object
. Technically, they are all objects, and are collectively referred to as Objects.
let students = ['Jane', 'Mike', 'Joan'];
students
reference variable keeps tab of the location of[‘Jane’, ‘Mike’, ‘Joan’]
in memory. However, reassigning a reference variable replaces the old reference.
Variable Reassignment and Mutability
In some instance, one may one want to keep a variable in an immutable state. In JavaScript, this can achieved by:
For non-primitives
var profile = { age: 24, increment() { this.age++ } };// increment age
profile.increment() => { age: 25, increment: f };// making this object immutable
Object.freeze(profile);// trying to increment age now won't work
profile.increment() => { age: 25, increment: f };
// profile.age remains unchanged.
For primitives
With the new ES6 syntactic sugar
, this can be easily achieved by using const
.
Number primitive data type
const age = 24;age = 25; // gives a TypeError of: Assignment of constant variable
So is the case for String
const name = 'Harry';
name = 'Henry' // same TypeError as above (Number)
In other words, name
and age
variables above are read only.
Point to note:
Using
const
on an object doesn’t create an immutablevalue
.
const person = {
name: 'Harry'}person.name = 'John';
console.log(person) => {name: "John"}
So, if you are looking to lock an object down, use:
Object.freeze()
instead.
Thanks for reading!