0

I'm a newbie in JavaScript and trying to learn about Objects and for..in loop.

Then I tried this code in the browser:

const dad = {
    gender: 'male',
    age: 53
}

for(let prop in dad){
    console.log(prop, dad[prop]);
}

It showed the result once, but then when I run again, the console says:

Uncaught SyntaxError: Identifier 'dad' has already been declared

I've tried to do some Google search and read through about scope and block scoping, but still not yet really understand

When I tried to block the code with an outer scope ( grap the code in a {} ) or put the code in a function, it works well.

Please help me understand this

  • 1
    you code looks fine. You probably best explain how did you run this piece of code (and I suspect there's more code to show). – Mario Vernari Apr 22 '20 at 10:01
  • 3
    Test this in an actual javascript file or wrap it in a function. If you test it in the console like that it won't work because it's like writing into one giant file, you are always in the same scope, so you can't declare the same variable again, it's "spoiled" until you reload the page (or possibly until you reopen devtools, not sure). – CherryDT Apr 22 '20 at 10:02
  • Ohh okay. I got it. Thanks for all the comments, Mario, Cherry and Bergi. I code in the ```Snipet```. –  Apr 22 '20 at 10:11

1 Answers1

0

The console does run code snippets in the global scope. When you've run const dad for the first time, it does declare a global variable. You now can refer to dad in subsequent code. When you try to run it a second time, it complains that it already is declared - just as if you had written

const dad = 1;
const dad = 2;

If you want to start fresh, reload the page.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375