Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBenjamin Hedgepeth
5,672 PointsVariable Initialization in Javascript
I'm extremely confused with the initialization stage when it comes to variable statements
http://www.ecma-international.org/ecma-262/6.0/#sec-variable-statement
Var variables are created when their containing Lexical Environment is instantiated and are initialized to
undefined
when created.
Initialization is the means of assigning an initial value to a variable. So undefined
is the initial value of a declared variable.
Seeing this though various times;
var thing = "code";
The variable thing
is initialized with "code"
.
How is this possible? Initializing a variable that is already initialized does not make any sense to me at all. In other words, how can a variable be initialized when it already has an initial value?
1 Answer
Steven Parker
231,275 PointsIn your example, the variable "thing" is being created for the first time.
If it already existed (initialized or just declared), there would be no "var" in front of the name and this would be a simple assignment.
Benjamin Hedgepeth
5,672 PointsBenjamin Hedgepeth
5,672 PointsI understand that. Please watch this video:
https://www.youtube.com/watch?v=6vBYfLCE9-Q
He says a variable is initialized with a value of
undefined
. Then he goes on to say that same variable is initialized with a string.From MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
How is it that there is an option to initialize a variable when it's automatically initialized with a default value by JavaScript when it is declared?
Steven Parker
231,275 PointsSteven Parker
231,275 PointsI think what he meant to say was, "Variables are implicitly initialized to a value of
undefined
by default when they are created." So that only happens if they are not initialized explicitly. For example:The reason there is an option to explicitly initialize a variable when you declare it is so you don't need to assign it in a separate step.