While coding in a Node.js REPL, I accidentally declared a new symbol
by using the new
keyword and since Symbol()
is not a constructor, I got an error as shown in this snippet,
let sym = new Symbol("some description");
// TypeError: Symbol is not a constructor
// at new Symbol (<anonymous>)
So I thought that's fine, I'll do it the right way but I got another error.
let sym = Symbol("some description");
// SyntaxError: Identifier 'sym' has already been declared
That was strange to me because I expected that since my declaration caused an error, the variable has not been defined at all but now I see it seemingly is defined. My next guess was that maybe it got an undefined
value, so I tried to reach to this variable and see what value it owns.
console.log(sym);
// ReferenceError: sym is not defined
WHAT? So the variable sym
is both defined and undefined?
I even tried to use the block scope of an object so that I can check whether the variable does actually exist in the object using the Object.prototype.hasOwnProperty()
function but unfortunately, the same problem emerged and the whole object became undefined and inaccessible.
let obj = {
a: 4,
b: new Symbol("some description"),
};
// TypeError
console.log(obj);
// ReferenceError
let obj = {};
// Syntax Error
I found that this issue could go away if I use var
declarations, so I assume it has something to do with block scopes that I don't know.
So I have 3 questions with respect to this problem:
Where is the variable
sym
defined and where is it undefined? Any connection between this case and the idea of "Temporal Dead Zone"?What value does
sym
own?How can I assign a new value to the
sym
variable?Is this problem specific to this case or any erroneous let/const declaration will result in the same issue?