Reputation: 23
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}`;
}
Upvotes: 1
Views: 521
Reputation: 138257
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
Upvotes: 2