The difference between consts which preserve value and consts which preserve references, reflects the difference between variables that get passed by value and those which get passed by reference.
When a variable holding a primitive value gets passed to a function, the value gets copied into function's parameters ("pass by value"). The function can make changes to the value without affecting the variable's value outside the function. This holds for variables declared with var, const or let. I see a symmetry between the value's immutability, when declared with const, and the pass-by-value rules.
var bar = 'bar'
const baz = 'baz'
let qux = 'qux'
function makeFoo(fromParam) {
fromParam = 'foo'
return fromParam
}
makeFoo(bar) // "foo"
bar // "bar"
makeFoo(baz) // "foo"
baz // "baz"
makeFoo(qux) // "foo"
qux // "qux"
When a variable holding a complex value (variations of Object) gets passed to a function, the function cannot change the reference (pass by reference), but it can change properties of the passed object. This reflects the mutability of complex consts.
I found this observation helped me cement my knowledge about which aspects of variables const protects.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The difference between
const
s which preserve value andconst
s which preserve references, reflects the difference between variables that get passed by value and those which get passed by reference.When a variable holding a primitive value gets passed to a function, the value gets copied into function's parameters ("pass by value"). The function can make changes to the value without affecting the variable's value outside the function. This holds for variables declared with
var
,const
orlet
. I see a symmetry between the value's immutability, when declared withconst
, and the pass-by-value rules.When a variable holding a complex value (variations of Object) gets passed to a function, the function cannot change the reference (pass by reference), but it can change properties of the passed object. This reflects the mutability of complex
const
s.I found this observation helped me cement my knowledge about which aspects of variables
const
protects.