1

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}`;
 }
Jonas Wilms
139k20 gold badges164 silver badges164 bronze badges
asked Jan 23, 2021 at 2:51
1
  • 1
    First, those variables are not being reassigned inside that scope, therefore const is fine. Second, in general, if you aren't going to change a variable later you should always use const and with you'll enforce this habit with linters. Third, using let instead of const is fine, your answer is correct, but see my second point. Commented Jan 23, 2021 at 2:56

1 Answer 1

2

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
answered Jan 23, 2021 at 3:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.