Why is it that this gives an error:
var a = [c];
// ERROR: c is not defined
but this does not (but results in an undefined):
var a = [c];
var c = 'x';
console.log(a); // [undefined]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s called
hoistingand means, that your Javascript engine willdeclareallvarstatments andfunction declarationsat parse time. In other words, all yourvarstatements have already been declared (but not defined) when that script is executed.That can be trouble sometimes. Example:
If we run
what(), we get thehuh, where is foobar??message. This is because within the execution context ofwhat, the variablefoobargets declared(not defined) when the interpreter reads our code. Declarations are alwaysundefined. It doesn’t matter where thevarstatement exists within a context! it always gets “hoisted up”.A good advice to totally avoid that kind of error is, to declare AND define all of your used variables at the top of each context/function.
Now looking at your example code, we can answer easily what happens.
As soon as our javascript interpreter reads that code, it’ll declare the variables
aandc. This will look likeor, even more expresive