75

ES6 onwards we have const.

This is not allowed:

const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;

This makes sense because it prevents us from using the constant before it's initialized.

But if I do

if(condition)
    const x = 5;

else 
    const x = 10;

x becomes block scoped.

So how to conditionally create a constant?

1
  • 1
    This is something I miss in Javascript which Java did very well
    – WORMSS
    Sep 4, 2018 at 12:46

3 Answers 3

84

Your problem, as you know, is that a const has to be intialised in the same expression that it was declared in.

This doesn't mean that the value you assign to your constant has to be a literal value. It could be any valid expression really - ternary:

const x = IsSomeValueTrue() ? 1 : 2;

Or maybe just assign it to the value of a variable?

let y = 1;
if(IsSomeValueTrue()) {
    y = 2;
}

const x = y;

You could of course assign it to the return value of a function, too:

function getConstantValue() {
    return 3;
}

const x = getConstantValue();

So there's plenty of ways to make the value dynamic, you just have to make sure it's only assigned in one place.

4
  • 1
    Function way is cleaner if we have long conditions and calculations (as in my case) which would look messy using ternary operator. Aug 4, 2016 at 11:05
  • 1
    I agree that the function method is probably the cleanest, especially for more complicated conditions. Just pick whatever method best fits your use case :)
    – Hecksa
    Aug 4, 2016 at 11:15
  • I prefer the final option (function), since it lets you change, reuse, or even unit test the logic without depending on the rest of the class.
    – ssube
    Aug 4, 2016 at 17:44
  • While the other answers are correct as well, accepting this because it shows different methods. Aug 5, 2016 at 5:10
32

If ternary operator isn't an option for its unreadability, the only other option is IIFE, which is cumbersome but can be read fluently:

const x = (() => {
  if (condition)
    return 5
  else
    return 10
})();

The semantics of const is that it is assigned once. It should be let for this use case:

let x;
if(condition) x = 5;
else x = 10;

From my personal experience, ~95% of variables are const. If a variable has to be be let, just let it be itself; the probability of bugs caused by accidental reassignments is negligible.

5
  • 1
    IIFE seems like the neatest solution given the use case defined in the comments by OP Aug 4, 2016 at 15:25
  • 7
    If a ternary isn't readable, how on earth is an IIFE better? That's significantly less readable.
    – ssube
    Aug 4, 2016 at 17:44
  • 5
    @ssube IIFEs are established language constructions that can be automatically interpreted by fluent JS speakers, arrows make them slimmer, proper indentation and brackets help, too. This is subjective, but it should be noticed that there's no word 'better' in the answer, and the word 'earth' doesn't make the argument more valid. The fact that IIFEs don't work for you doesn't mean that they don't work for everyone, thanks for the commented downvote anyway. Aug 4, 2016 at 18:03
  • 2
    IIFEs have their time and place, but this can be solved with a regular call to a sibling method. Using an IIFE just to inline that method (which the JIT will do on its own) just leaves you with a lot more complexity than even the ternary.
    – ssube
    Aug 4, 2016 at 18:22
  • @ssube I like the IIFE solution because it indicates a one-time assignment. If this required a named method, for reuse, i'd consider whether this should be a const at all. Readability of this is better than a ternary for the OPs use case because they require complex logic and repetition. I think that's what they're getting at with that first sentence Aug 8, 2016 at 8:50
9

Assuming that the const is going to be declared in both instances, you could use a ternary assignment:

const x = condition ? 5 : 10;
5
  • I guess they are taught that ternary :? is an evil, non-readable style. It defeats repeat yourselfprinciple, that so called 'readability' is based on :) Aug 4, 2016 at 10:51
  • If I'm declaring multiple constants I'd have to repeat the condition for each of them. x = cond ? a : b; y = cond ? e : f Aug 4, 2016 at 10:56
  • 3
    @ArjunU. Read const [a,b] = [x,y] assignment. Aug 4, 2016 at 10:57
  • Oh yeah destructuring. Fantastic! Aug 4, 2016 at 11:00
  • @ArjunU. Effectively yes. Otherwise you'd have to introduce unnecessary variables Aug 4, 2016 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.