r/javascript • • Oct 24 '16

help The only thing I hate about const ...

... is that it is 5 chars long.

For some reason, let with its 3 chars, looks more elegant.

7 Upvotes

49 comments sorted by

View all comments

0

u/0x13mode Oct 25 '16

const has other disadvantage, as well. You can't postpone assignment, e.g.

const a; //error!!!!! Uncaught SyntaxError: Missing initializer in const declaration

if (true) {

a = 1;

} else {

a =2

}

but you have to use let. Or var.

1

u/CWagner Oct 25 '16

const t = a ? 1 : 2;

1

u/0x13mode Oct 25 '16

this is simplest case and sometimes ? : is god but sometimes/often ? : it's not very readable (complex conditions etc.)

Besides this doesn't have to be condition. Problem is not with a condition but that const forces to assign variable during declaration. Even if you're planning to assign variable just once and treat it as a constant after that, you can't do it using const (afaik).

3

u/atubofsoup Oct 25 '16

You could use an IIFE:

const foo = (() => {
  const a = 5;
  const b = 10;
  return a + b;
})();

It's not very pretty though.

1

u/0x13mode Oct 29 '16

you're right (you and @AceBacker) that sometimes function/IIFE can be solution to that (especially if we have simple => syntax)