Object created with "let" causes an error. "var" does not

I have noticed while going through the Javascript/First_Steps/Variables tutorial, that I receive a syntax error message when using the suggested “let” declaration to create the object named “dog”.
When I copy the code listed here: // begin quoted bit
let dog = { name : ‘Spot’, breed : ‘Dalmatian’ };
dog.name //end quote
This throws an error in my browsers developer tools: //begin error
Uncaught SyntaxError: redeclaration of var dog
debugger eval code:1
//end quote

However, when I use the term “var” instead, I don’t get the error message. (the console logs the name “Spot” with no problem)

What could be causing this error? Yes, this is a beginner question I am certain.
The tutorial suggests that using “let” is preferable to “var” so I would like to cooperate with this instruction, but not so much when “let” causes the console.log to stop progress.

here is the tutorial page I am referring to:

Any input is appreciated.
MJ

Hi @outaroom and welcome to the community :wave:

It’s possible to declare var variables inside the same scope multiple times. This could lead to problems:

var dog = {name: 'Toby'};
/* 100 lines of code later we need to save another dog
   into a variable but forgot about Toby */
var dog = {name: "Freddy", age: 5};
console.log(dog); /* Object { name: "Freddy", age: 5 } */
/* Poor Toby is no more :-(
   We should have used "var dog2" for Freddy */

This is called “redeclaration” and is no longer allowed with the newer and better let statement and throws an error to prevent this error.

Why does that happen in the console?
Until you reload the page every simple variable declaration with var, let and const is in the same scope in your console (like writing them all in the same “.js”-file). You have probably written let dog = ... in the console and then to test something else let dog = ... again (or first var an then let).

I hope this explanation is understandable. Feel free to ask more questions. :slightly_smiling_face:

Happy Coding!
Michael

1 Like

AH!!
Thank you Michael.

That was spot on.
MJ

1 Like