DEV Community

loading...

Discussion on: Confused by JavaScript's const? Me too!

Collapse
simondell profile image
Simon Dell

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.