You will find these keywords, val
, var
, let
, const
, static
, and def
used across these languages to define a variable, i.e. JavaScript, Swift, and Scala, as seen below.
A simple thinking is that if the keyword is the same, then the behavior is the same across the languages. Unfortunately, they are of different meanings sometimes.
Hence I’m writing here to share about them for a quick comparison.
This is the var
in JavaScript, that is unique to this “wild-wild west” language that can do almost anything. No other languages (above) has this attribute, except for JavaScript.
Below are some very interesting attributes it has.
// JavaScript
var x = 10
x = 11 // reassign to mutate the value
console.log(x) // result 11
// JavaScript
var x = 10
var x = 11 // this is okay
console.log(x) // result 11
// JavaScript
function test() {
{
var x = 10
}
console.log(x) // accessible and result is 10
}
Note, it can’t be accessed outside the function though. Therefore it is also called a function scoped variable.
This means if it is defined at the global scope, it will stick to the window
var stickyVariable = 10
window.stickyVariable // available in window and result as 10
Using this type variable is pretty risky as it easily gets mutated and can affect and be affected by 3rd party libraries variable setting if the name collide. It is there as pre ES6, that’s the way JavaScript has its variable defined.
When I term normal, I mean the life of the variable is limit within the scope where it is defined i.e. { /* scope is covered by curley brackets */ }
.
A mutable variable is a variable that CAN be changed (reassigned) with a new value after being created.
var
.let
.After a variable has been created, it cannot be created anymore
// JavaScript
let x = 10
let x = 11 // Error: Identifier 'x' has already been declared
However, it can be reassigned
// JavaScript
let x = 10
x = 11 // this is okay
console.log(x) // result 11
When I term normal, I mean the life of the variable is limit within the scope where it is defined i.e. { /* scope is covered by curley brackets */ }
.
An immutable variable is a variable that CANNOT be changed (reassigned) with a new value after being created.
var
.let
(don’t mix up with the let
in JavaScript).const
// JavaScript
const x = 10
x = 11 // Assignment to constant variable
#software-development #web-development #programming #software-engineering #mobile-app-development #mobile-app