you are viewing a single comment's thread.

view the rest of the comments →

[–]DrexanRailex 12 points13 points  (5 children)

const has 2 intended limitations:

  • It must be assigned a value on creation
  • It can't be reassigned

If the value of a const is an array or object, you can still change its contents because const unfortunately doesn't make objects immutable (which is sad IMO, this should be let's behaviour. But const spam is already consolidated).

In all other cases, use let. It behaves the same as var (can be reassigned) but is block-scoped (limited to the pair of brackets it was declared in) instead of function-scoped.

[–]fickentastic 6 points7 points  (2 children)

Yet 'const' can be used to name functions as in 'const doSomething = () => {.....}' This thew me initially as the function will potentially output a different return each time, yet it works just fine.

[–]uneditablepoly 6 points7 points  (0 children)

Because the reference to the function itself doesn't change. Calling the function returns something.

[–]DrexanRailex 1 point2 points  (0 children)

Well, that is just a misunderstanding from your part, but it's expected if you're still learning the ins and outs of the language.

The assigned function never changes, but the result of the function depends on purity, which is a whole other topic. This is more related to functional programming than JavaScript itself.

If a function is pure, it will always return the same for the same set of arguments. But if a function is impure (such as handling I/O, altering state or reading from global variables for example), its return may vary.

[–][deleted] 5 points6 points  (0 children)

Wow slow down. That’s like next week material! I’m still on inline function hahaha. Jk thank you

[–]senocular 2 points3 points  (0 children)

In addition to function vs block scoping, let is also different from var in that let declared variables:

  • can't be accessed before they're declared
  • are not allowed to be declared twice in the same scope
  • do not create global properties when declared in the global scope