es6-interactive-guide icon indicating copy to clipboard operation
es6-interactive-guide copied to clipboard

Weird const in the arrow functions demo

Open codepo8 opened this issue 10 years ago • 5 comments

You're defining the double in the last example as a const, however it gets changed on every application of the map. let would make more sense, wouldn't it?

codepo8 avatar Oct 12 '15 23:10 codepo8

It's not really getting changed though on each call since each call has its own scope within the function; the declarations don't "carry over" on each call. eslint would actually warn you of an unnecessary use of let.

exogen avatar Oct 12 '15 23:10 exogen

True, it does seem to be an odd use of const though as it is never re-used. Maybe a simple var should do the trick. It's not a mistake, but it seems a weird use, seeing that defining a const is a statement of "this won't change"

codepo8 avatar Oct 12 '15 23:10 codepo8

I'd personally change the whole function to return number * number * number; myself, the separate declaration is indeed kinda confusing no matter how it's declared. But FWIW, eslint would warn of var as well since it recommends only let or const.

exogen avatar Oct 13 '15 00:10 exogen

I agree with that option. Much less contrived. Or to make it shorter return Math.pow(number, 3)

On Tue, Oct 13, 2015 at 1:17 AM, Brian Beck [email protected] wrote:

I'd personally change the whole function to return number * number * number; myself, the separate declaration is indeed kinda confusing no matter how it's declared. But FWIW, eslint would warn of var as well since it recommends only let or const.

— Reply to this email directly or view it on GitHub https://github.com/FormidableLabs/es6-interactive-guide/issues/11#issuecomment-147554309 .

codepo8 avatar Oct 13 '15 00:10 codepo8

number * number * number is definitely better. However:

seeing that defining a const is a statement of "this won't change"

It's a bit more nuanced than that. const is really a statement of "this won't be reassigned within the context of this block, and specific to this invocation". Thinking of a const in terms of "this won't change" can lead to incorrect assumptions. For example, const a = {}; a.val = true; is perfectly valid - a is not reassigned in this case, but the object that a references can change.

In the arrow-function example, const should be preferred over var (even though the line itself is unnecessary) because a's assignment doesn't change within the context of each invocation. In fact, I would argue that there is no longer a need to use var anywhere, assuming an ES2015+ environment.

divmain avatar Oct 13 '15 00:10 divmain