News for hackers. Stuff that matters.
Re:Constantly Confusing ‘const’ by codecurve on Tuesday September 08, 2015 @02:07PM (#10187302)
Why not use `const` as default? I would argue that using `let` instead is a premature optimization of readability.

It's easier to reason about a variable if you know it will always be one value—even if the value may be mutated (which is unfortunate).

`const` is a simpler construct. It has less rules and I would always suggest that using `let` will introduce complexity that only needs to be there when you can identify a genuine need to re-assign a value to your variable.

That said, I enjoyed the post. It's a good read!

Re:Constantly Confusing ‘const’ by braythwayt on Tuesday September 08, 2015 @02:58PM (#10187538)

  > It's easier to reason about a variable if you know it will always be one value—even
  > if the value may be mutated (which is unfortunate).
True, but because const, let, and var are lexically-scoped, it’s super-easy to reason about everything that happens to variables. (Excepting bad JS environments where you can declare global constants, of course).

If I see PI = 3.14159265 somewhere in a file, it’s not a hardship to assume it will not be rebound, and to notice if it is rebound.

The super-important thing to reason about is value mutability, because that escapes lexical scope. We pass mutable values to library functions containing code we have never read. We integrate with code written by a colleague who is in another time zone and may accidentally change a routine to mutate an array we pass with .push instead of .concat.

“Easier to reason about” is massively important with mutability. Not so much with lexical bindings.

Re:Constantly Confusing ‘const’ by codecurve on Tuesday September 08, 2015 @03:18PM (#10187639)
Totally agree, it is much more important to be able to reason about mutability.

I would disagree that it's super-easy to reason about var, despite being lexically scoped. It still causes an enormous amount of confusion when loops and callbacks are used together.

The PI example only really works because we all know what PI should look like. If you were using someone else's constant value and it accidentally got rebound it would be much harder to know.

Re:Constantly Confusing ‘const’ by braythwayt on Tuesday September 08, 2015 @03:23PM (#10187660)
Fair enough about var, it is annoying in ways that are orthogonal to rebindability (is that a word?)

Also, here’s my question: If I can write:

  const PI = 3.14159265;
Why can’t I write:

  const function diameter (r) { return 2 * PI * r; }
???
Re:Constantly Confusing ‘const’ by codecurve on Tuesday September 08, 2015 @03:55PM (#10187859)
Probably for the same reasons you can't write

    var function diameter() {}
It's definitely a shame that the only way to achieve consistent behaviour between variables and named functions requires you to write the name twice.

    const diameter = function diameter() {};
If it wasn't for the usefulness of named functions for debugging and hoisting, I would just use:

    const diameter = function() {};
Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @04:01PM (#10187890)
Except that any variation of these doesn't produce the same thing as a declaration, since function declarations hoist and function expression assignments do not.

Most people don't like hoisting -- and I agree that variable hoisting is crazy. I'd never advocate this:

    a = 2;
    var a;
But function hoisting I find super useful. I always prefer to write my files like this:

    foo();
    bar();
    
    // ....
    
    function foo() { .. }
    
    function bar() { .. }
...because when I open a file, I don't want to go hunting for any executable code, I just want to look at the very top. Function declaration hoisting lets me put those definitions at the bottom and the code that uses them at the top.

I've found this to be much more useful in code maintenance.

Re:Constantly Confusing ‘const’ by clessg on Tuesday September 08, 2015 @04:17PM (#10187978)
I agree on function declarations even though I avoid hoisting in other situations. I don't see any serious downsides to using function declarations (unless within a function, perhaps), and I find it easier to read, especially in ES6: `export function diameter` vs. `export const diameter = ...`.
Re:Constantly Confusing ‘const’ by mquander on Tuesday September 08, 2015 @04:37PM (#10188084)
If you just write everything in order of usage, the executable code still winds up in a very easy-to-find place -- the very bottom, rather than the top.
Re:Constantly Confusing ‘const’ by pixel67 on Wednesday September 09, 2015 @09:39AM (#10191339)
That's how I write my JS as well. It's like speaking
Re:Constantly Confusing ‘const’ by clessg on Tuesday September 08, 2015 @04:03PM (#10187899)
Actually, I believe arrow functions keep the name of the binding.

    const diameter = () => {};
    export const radius = () => {};
Could be wrong.
Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @04:05PM (#10187909)
What you're thinking about in ES6 is called "function name inference" and only refers to certain forms, like this one, where the name -- PURELY FOR DEBUGGING -- can be inferred. Actually, it goes for all assignments, `var`, `let`, and `const`.

Otherwise, the arrow itself is anonymous and thus you don't have a name to make an inner self-reference with.

Re:Constantly Confusing ‘const’ by throwaway3453 on Tuesday September 08, 2015 @04:03PM (#10187897)
What you have written is a function statement rather than a function expression.

This is possible, but has no utility beyond the original.

    const diameter = function diameter (r) { return 2 * PI * r; }
Re:Constantly Confusing ‘const’ by braythwayt on Tuesday September 08, 2015 @09:19PM (#10189147)
As other comments have noted, I a speaking to the fact that you can’t make a function declaration while also specifying that the name is not to be re-bound within its scope.

A function expression bound to a constant block-scoped variable does not have the exact same semantics.

Re:Constantly Confusing ‘const’ by megaman22 on Tuesday September 08, 2015 @03:50PM (#10187827)
What is the goal of marking that function const? Is it to prevent redefining the function, or as a hint that it is a pure function and it's outputs can be memoized?
Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @03:59PM (#10187877)
Yeah, see, this is exactly the problem. I think most developers assume the latter, when the former is all that's meant according to JS.

I don't think the former is all that useful, and the latter is super useful but `const` doesn't do anything to help with that.

Re:Constantly Confusing ‘const’ by jdeisenberg on Tuesday September 08, 2015 @04:14PM (#10187964)
The fact that you can redefine a function gives me a terribly unsettled feeling, probably because I remember the assembly language days when we were told not to write self-modifying code, as it's not re-entrant. (If JS were ever in a concurrent environment, would re-defining functions lead to problems?)
Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @02:14PM (#10187337)
> Why not use `const` as default?

The argument I made toward the end of the post is that refactoring from `const` back to `let` is more risky than the other way around.

Moreover, surveying my own code, honestly, the vast majority of my declarations should be `var` or `let`, and only a much smaller amount being `const`. I think a lot of people are rushing blindly to `const` without realizing its full behavior.

> [`const`] has less rules ... using `let` will introduce complexity

I think this is completely backwards. `let` has no special caveats (other than the TDZ thing, which they both have), whereas `const` has this caveat that it's only about assignment bindings and not about values.

Imagine a piece of code that has `const x = 2` that you later refactor to `const x = [2]`. The complexity is, you now have to contend with the `[2]` being a mutable value where `2` wasn't, and `const` sorta pretends to keep you safe but doesn't.

That's the complexity I disfavor.

Re:Constantly Confusing ‘const’ by adrusi on Tuesday September 08, 2015 @04:11PM (#10187948)
`const` has this caveat that it's only about assignment bindings and not about values.

Imagine a piece of code that has `const x = 2` that you later refactor to `const x = [2]`. The complexity is, you now have to contend with the `[2]` being a mutable value where `2` wasn't, and `const` sorta pretends to keep you safe but doesn't.

If these semantics aren't instantly obvious to you, then that's emblematic of a serious gap in your understanding of programming. I say this not with the intent of shaming, but to recommend that you (and the very many other people with the same lapse) invest some time into developing intuition about reference semantics. The best way IMO is to get initmately familiar with a language that has first class pointers or otherwise explicit indirection. Learn C, get good at C, write something big in C. Focus on the pointer semantics and you'll come out a significantly better programmer in languages where pointers are slightly less immediately visible.

Of course if you're making this recommendation because you work with other people who have a lapse in their understanding of references I can understand that. I would encourage you, however, to try to fix the problem rather than work around it by stunting the language. After all, it's an issue that will crop up everywhere, not just the semantics of `const'.

Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @04:17PM (#10187980)
Oh, I see. I just need to learn more. The problem is I just don't know JS (or other langs for that matter).

http://YouDontKnowJS.com

Re:Constantly Confusing ‘const’ by abritinthebay on Tuesday September 08, 2015 @05:48PM (#10188394)
I agree that saying this issue is "emblematic of a serious gap in your understanding of programming" is.. well.. douchebaggery.

However I feel a lot of the article and many of your posts about it in here come down to "it makes me feel uncomfortable" which.. I mean, ok. Sure. I hate spaces for indentation and think double quotes are better (and I have reasons for both)... but I don't say there's no use to the other options.

I feel you're throwing the baby out with the bathwater here.

Should const probably have been about value immutability too? Yes, I think so. I totally agree. That's a REALLY important topic to discuss. Maybe pitch it to the ES2016 committee as an iterative upgrade to const?

But as it stands it does have value. Yes it mostly just codifies what programmers original did as a language construct but it does also stop redefinitions which was an annoyingly common issue. So it's progress. Small, incremental, and not as full-featured as we'd both like... but it's progress.

Drawing attention to the issues with const is important... but there's no reason to rail so hard against its usage when it's understood to have those limitations... is there?

Re:Constantly Confusing ‘const’ by _getify on Tuesday September 08, 2015 @07:43PM (#10188847)
But my post did actually conclude the cases where it's useful. It seems like a lot of people here only read the first half of the post and stopped.

I don't think `const` should be removed. I just don't think we should lead with it. I'm not sure why that's not coming across except for the fact that the post isn't being read.

Re:Constantly Confusing ‘const’ by abritinthebay on Wednesday September 09, 2015 @12:50AM (#10189749)
Hmmm I think maybe your tone comes across stronger than you mean it then.

Because, while you do say that, it comes across as a sort of "meh, it's not totally useless but I still hate it" kind of thing at the end.

Especially as you spent the last... like 2000 words trashing it.

Re:Constantly Confusing ‘const’ by aquilaFiera on Tuesday September 08, 2015 @03:18PM (#10187644)
Using the mantra code is communication, declaring everything as const lets others (and your future self) know that as of last writing they can expect this variable to not be reassigned. I think that small piece of information can be useful.

To your point however, `const` does not imply constant in the sense of other languages (like `.freeze()` does) so it does mean your target future audience is someone who is familiar with some of the nuances of recent JavaScript, an assumption that can be dangerous to make.

For my recent ES6 escapades I've been using the pattern of `const` first and `let` only when mutability of assignment is needed and I have yet to have that bite me in the ass. However this has been small projects and I can't speak for a larger codebase.

Re:Constantly Confusing ‘const’ by Nullabillity on Tuesday September 08, 2015 @06:14PM (#10188502)
> To your point however, `const` does not imply constant in the sense of other languages (like `.freeze()` does) so it does mean your target future audience is someone who is familiar with some of the nuances of recent JavaScript, an assumption that can be dangerous to make.

Does any other language than Rust implement it this way? I know Rust needs to, for the borrowing semantics.

Java does it the same way as JS. Scala and Haskell both make everything immutable by default as convention, but there's nothing preventing you from mutating a `var` field of a `val` reference, or abusing `unsafePerformIO` to modify an `IORef` from a supposedly pure context.

Re:Constantly Confusing ‘const’ by jharger on Tuesday September 08, 2015 @06:39PM (#10188598)
C++

Assume you have a class Foo, and this:

const Foo fooInst(1, 2, 3);

if you try to call a method foo.bar() you can't, unless that method bar() is also marked const with this type of signature:

int bar() const;

Meaning that bar returns an int, but can't assign to any fields or call any other non-const methods.

Although, it does have this hideous const_cast<> operator that anyone can use to break these rules.

Re:Constantly Confusing ‘const’ by codecurve on Tuesday September 08, 2015 @02:46PM (#10187490)
I think that completely depends on the flavour of code you write. If you mostly use imperative styles, then the large proportion of your declarations will be `var` and `let`. It definitely makes refactoring harder in the direction you mentioned.

Alternatively, for a functional style, you have to have a fairly good reason for using `var` or `let`. I find myself treating them like I'd treat atoms in Clojure. They end up being the mechanism you use to make controlled side-effects.

I'll concede that `const` does have a complexity to understand...initially. However once you understand the distinction between assignment and value (you only have to understand it once), then you're back to a level playing field between both.

From then on, `const` gives you a guarantee about the assignment. Objectively, this guarantee eliminates complexity, you can look at a variable anywhere in a scope and know that it has the same value as at time of declaration (same TDZ exceptions apply). I don't see how this could be seen as backwards.