Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Conditionally initializing a constant in Javascript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...