Keyword 'Const' Does Not Make the Value Immutable. What Does It Mean

Keyword 'const' does not make the value immutable. What does it mean?

MDN sums it up nicely:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.

More succinctly: const creates an immutable binding.

In other words: const, like var, gives you a mutable chunk of memory in which you're storing something. However, const dictates that you must keep referring to that same chunk of memory – you can't reassign the variable to a different chunk of memory, because the variable reference is constant.

To really make something constant and unchanging after you've declared it, you need to use something like Object.freeze(). However, that's shallow and only works on key/value pairs. Freezing an entire object takes a bit more effort. To do so repeatedly in a performant way is yet more challenging. If you really have a need for that, I'd recommend checking out something like Immutable.js

What's different about 'const' keyword placement in Dart?

The const as keyword makes your object constant where you are not able to reassign any value to it later.

Const means that the object's entire deep state can be determined entirely at compile-time and that the object will be frozen and completely immutable.

In your example

list1 = []; // perfectly fine
list2 = []; // but this throw errors (Error: Can't assign to the const variable 'list2'.)

On the other hand, var allows you to reassign value to the variable.

However, the const after the value makes the value unmodifiable let's take a look at an example

list1.add(22); // ERROR! Cannot add to an unmodifiable list
// but you still can reassign the value
list1 = [];
// while the
list2 = []; // throw errors as I said above!

the const for the value in const keyword variable is hidden.

const list2 = const [1,2,3];
list2.add(22); // ERROR! Cannot add to an unmodifiable list

In Short: One makes the memory allocated immutable, the other one the same, and also the pointer pointing to it. in both cases, the list(object) will be immutable.

I hope this helps you understand the difference.

Read more from offical documentation on dart.dev/language-tour#final-and-const

JavaScript const Keyword

Yes, it does create an immutable reference, but it is not been standardized and is not supported in all browsers.

See this MDN article on the const keyword for details and compatability.

However, it doesn't do anything to set the referenced data structure as immutable. Several answers below address that question using, for example, Object.freeze

How to completely restrict the modification of properties of a const object

Okay - so it is required to use Object.freeze call t make the object unchangeable.
Even the strict mode isn't required.

const x = {a:"sss"}
Object.freeze(x);

x.a = "k"
console.log(x)

Outputs:

x.a = "k"
^

TypeError: Cannot assign to read only property 'a' of object '#<Object>'

What is the difference between immutable and const variables in Rust?

const, in Rust, is short for constant and is related to compile-time evaluation. It shows up:

  • when declaring constants: const FOO: usize = 3;
  • when declaring compile-time evaluable functions: const fn foo() -> &'static str

These kinds of values can be used as generic parameters: [u8; FOO]. For now this is limited to array size, but there is talk, plans, and hope to extend it further in the future.

By contrast, a let binding is about a run-time computed value.

Note that despite mut being used because the concept of mutability is well-known, Rust actually lies here. &T and &mut T are about aliasing, not mutability:

  • &T: shared reference
  • &mut T: unique reference

Most notably, some types feature interior mutability and can be mutated via &T (shared references): Cell, RefCell, Mutex, etc.


Note: there is an alternative use of mut and const with raw pointers (*mut T and *const T) which is not discussed here.

What is the absolute significance of const?

First of all, it’s a good idea to stop using var if you are writing ES6. Simply use const for constants and let for variables.

The first example crashes because you are redefining a const which is already defined in that scope. Same thing would happen when redefining a let variable. I know var allows redefining, but this makes the code hard to read.

The second example works as expected because you are defining the constant in a new scope. The example bellow would also work.

<script>
const x = 10;
{
const x = 2;
}
</script>

Bottom line: you can't redefine variables [let] and constants [constants] in the same scope.

What is the difference between the const and final keywords in Dart?

There is a post on dart's website and it explains it pretty well.

Final:

"final" means single-assignment: a final variable or field must have an initializer. Once assigned a value, a final variable's value cannot be changed. final modifies variables.


Const:

"const" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.

Const objects have a couple of interesting properties and restrictions:

They must be created from data that can be calculated at compile time. A const object does not have access to anything you would need to calculate at runtime. 1 + 2 is a valid const expression, but new DateTime.now() is not.

They are deeply, transitively immutable. If you have a final field containing a collection, that collection can still be mutable. If you have a const collection, everything in it must also be const, recursively.

They are canonicalized. This is sort of like string interning: for any given const value, a single const object will be created and re-used no matter how many times the const expression(s) are evaluated.



So, what does this mean?

Const:

If the value you have is computed at runtime (new DateTime.now(), for example), you can not use a const for it. However, if the value is known at compile time (const a = 1;), then you should use const over final. There are 2 other large differences between const and final. Firstly, if you're using const inside a class, you have to declare it as static const rather than just const. Secondly, if you have a const collection, everything inside of that is in const. If you have a final collection, everything inside of that is not final.

Final:

final should be used over const if you don't know the value at compile time, and it will be calculated/grabbed at runtime. If you want an HTTP response that can't be changed, if you want to get something from a database, or if you want to read from a local file, use final. Anything that isn't known at compile time should be final over const.


With all of that being said, both const and final cannot be reassigned, but fields in a final object, as long as they aren't const or final themselves, can be reassigned (unlike const).

What is the difference between const and val?

consts are compile time constants. Meaning that their value has to be assigned during compile time, unlike vals, where it can be done at runtime.

This means, that consts can never be assigned to a function or any class constructor, but only to a String or primitive.

For example:

const val foo = complexFunctionCall()   //Not okay
val fooVal = complexFunctionCall() //Okay

const val bar = "Hello world" //Also okay

Const in JavaScript: when to use it and is it necessary?

There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so.

The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.

The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.



Related Topics



Leave a reply



Submit