Does the const
keyword in JavaScript create an immutable reference to immutable data structures? [I'm assuming that immutable data structures exist in JavaScript.]
For string
it appears to do so:
var x = "asdf";
const constantX = x;
alert("before mutation: " + constantX);
x = "mutated"
alert("after mutation: " + constantX);
output:
before mutation: asdf
after mutation: asdf
Yes that is right. A const would only declare a read-only named constant. Changing its value will have no effect.
Reference for const on MDN:
Here's the browser compatibility matrix.
For example:
first you aren't mutating the string, you're reassigning the reference.
You're right that
const
isn't available in all common browsers. But even if it were, it is not sufficient.const
will prevent the reference from being reassigned - but if you have a const reference to a mutable object, you haven't accomplished very much.So that brings us to your question, does js even have immutable data structures? No, js does not come with them. Immutable datastructures can be coded as a library - and assignment is not even defined, so
o.foo = 'baz'
doesn't even make sense. You have to write it asconst var o2 = o.assoc('foo', 'baz')
which will return a brand new objecto2
instead of mutatingo
But immutable data structures as a library doesn't mean much if nobody uses them. E.g. if angular uses regular javascript datastructures, you have to use them too. Otherwise you'd have to convert between mutable and immutable at the boundary between your code and angular.
opinion follows:
IMO your only practical options for doing real functional programming for production browser apps is to wait around for something like ClojureScript to mature. ClojureScript reboots the library ecosystem, so as libraries get written, they use immutable datastructures by default.
You can of course do half-baked functional programming in javascript using tools like underscore.js and Facebook React, which is what I do for the production webapps I build. But you have to establish immutability by convention, and people are going to mutate things on accident or because they don't know any better and you have to deal with those challenges.
You can create CONST like values using ES5 Object.defineProperty. The crummy part is that it must be bound to an object
const is a proposed feature of ECMAScript(together with a properly block-scoped let it is supposed to replace var and implicit global). ECMAScript Harmony is a grab-bag of ideas for the next versions of ECMAScript.
If you looking for read only variable, you can do like this
You can use like this
Wrong. It is not immutable, from the MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const