Help with Firefox console behaviour

When learning JS I am using Firefox console.
Attached is a screenshot.
When I run it the first time it runs fine but then running it second time it complains - redeclaration of cons hobbies
Deleting the keyword const and it then complains about invalid assignment to const hobbies

Any explanation will be kindly apprecited

It is like this because you can not reassign the value of a const variable like that. If you do want to remove or add items to the array using the .push() (ex. hobbies.push('coding') and that adds coding to the array) to add an item to the array and .pop() (ex. hobbies.pop() //removes coding unfortently and this removes the last item witch is coding from the array.) to remove the last item in the array. Learn more here https://www.codecademy.com/courses/introduction-to-javascript/lessons/arrays/exercises/arrays or here https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-arrays/cheatsheet

Hi @ethanmastercoder
Thank you for taking the time to reply.
I am not sure about the relevance of your reply.
The code you see in the screenshot is a copy from Codecademy.
Here’s the original code from Codecademy:

const hobbies = ['singing', 'eating', 'quidditch', 'writing'];
 
for (const hobby of hobbies) {
  console.log(`I enjoy ${hobby}.`);
}

Running this code two times in firefox dev console is the same as executing this code:

const hobbies = ['singing', 'eating', 'quidditch', 'writing'];
 
for (const hobby of hobbies) {
  console.log(`I enjoy ${hobby}.`);
}

const hobbies = ['singing', 'eating', 'quidditch', 'writing'];
 
for (const hobby of hobbies) {
  console.log(`I enjoy ${hobby}.`);
}

It all happens in the same environment. So the constant hobbies is in fact already declared when you execute this code for the second time - thus the error.

You can refresh the window between runs.

Or you can place the code inside the block. const and let variables are block scoped. So you could write your code like this:

{
    const hobbies = ['singing', 'eating', 'quidditch', 'writing'];
 
    for (const hobby of hobbies) {
        console.log(`I enjoy ${hobby}.`);
    }
}

and you will be able to execute it as many times as you want. As const hobbies lives now in the inner scope.

1 Like

Ahh. Excellent.
Thank you @factoradic