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

Categories

0 votes
1.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}`;
 }
question from:https://stackoverflow.com/questions/65855248/const-redeclaration-javascript

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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...