Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

constants - Const Redeclaration Javascript

So i started learning Javascript a few weeks ago from an online course. I got up to a point where i started learning the DOM manipulation and there's an exercise to generate a random colours for the background. At first i saved the random colour to a let variable. But when i see the answer for the exercise, it uses a const not let. How is this possible, I thought const can't be redeclared?

 function randomColour() {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r},${g},${b}`;
 }

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

1 Answer

0 votes
by (71.8m points)

Whenever the function gets called, there is a new environment record which stores all the variables declared in the function. A const variable can be stored only once. If you call the function again, there is a new record, and as such the variable can hold another value.

 function a() {
   const b = Math.random();
    // assigning b again here won't work
 }

 a();  
 a(); // new record, new value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...