DEV Community

Discussion on: let var be const

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Good explanation of const. Though I find it really unfortunate that so many languages are adding this somewhat broken definition of what it means to be constant. In practice, a constant binding between a name and a value object isn't that helpful. I want actual constant value objects, not names.

Collapse
 
kayis profile image
K

Yes, I find this approach strange too.

I mean it looks like a constant, but it is re-assinged every call of the function it is declared.

I would expect a constant to be defined statically, like classes in most languages.

You have a module, it has constants, they are declared at import time, they can only be created with literals and other constants and this is it.

JavaScript uses the const keyword more like functional languages use let or val.

Collapse
 
hrmny profile image
Leah • Edited

Rust has actual constants and is immutable by default.

To make a variable mutable you add mut i.e. let mut number = 5;

If you don't add it and change it later in the code the compiler will throw an error.

This also applies to methods that change something in a vector (list) or a hashmap.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

I'd like to note that C/C++ have both concepts, but usually refer to value constness.

T const * ptr = expr;

The T value is const here, not the pointer. This is usually what we want. Compare to:

T * const ptr = expr;

The pointer is constant but the value is not. This is what const appears to mean in JavaScript, which is misleading based on it's syntax.

You can have both at the same time in C/C++:

T const * const ptr = expr;

Read the type form right-to-left to understand where const applies (the syntax rules are a bit ugly for this in C).