2

Why am I able to redefine a variable in browser console (eg. Chrome) but not in the console (Node) on terminal on my laptop( Mac).

Terminal Node Console:

> let varA = varB;
< Uncaught ReferenceError: varB is not defined
> let varB = "bla";
> let varA = varB;
< Uncaught SyntaxError: Identifier 'varA' has already been declared
> varA
< Uncaught ReferenceError: varA is not defined


//dropping let
> varA = varB;
< Uncaught ReferenceError: Cannot access 'varA' before initialization

Chrome Console:

> let varA = varB;
< VM510:1 Uncaught ReferenceError: varB is not defined
    at <anonymous>:1:12
(anonymous) @ VM510:1
> let varB = "bla";
< undefined
> let varA = varB;
< undefined
> varA
< "bla"
3

1 Answer 1

0

To intitialize a varaible you assign to it a value directly ex: name='foo' or you could declare the variable using this keywords, var,let,const

In your first example let varA = varB; you declared a variable with let keyword but you assigned to it and undeclared variable From MDN documentation

An attempt to access an undeclared variable results in a ReferenceError exception being thrown

as you will see in this example if you declare the variable before attempting to access it's value, it won't through an error but if you try to print it's value you get undefined because that's the default value javaScript gives to declared variables but without an assigned value

let varB
 let varA = varB;
 console.log(varA)

You get this error Uncaught SyntaxError: Identifier 'varA' has already been declared because you can't give a variable the same name in the same scope.

check this link also for more information

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.