Reputation: 2533
I'm new to JavaScript and would like to understand the order in which variable assignment takes place. Let's assume I have the following toy example:
var foo = document.sentence.split(',');
Do we split the sentence first, then assign the output of split
to the foo
variable? Or, do we first create the foo
variable, and then assign the output of document.sentence.split(',')
to foo
?
Thanks!
Upvotes: 1
Views: 395
Reputation: 7464
With var
things are a little different, because of hoisting.
Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.
However JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.
Example:
'option strict';
function myFunction() {
console.log(foo);
// => undefined
var sentence = 'my,array,of,strings';
var foo = sentence.split(',');
console.log(foo);
// => ['my', 'array', 'of', 'strings']
}
myFunction();
On the first console.log(foo)
we didn't get a Uncaught ReferenceError: foo is not defined
error. That's what would normally happen if we tried to access a variable that hadn't been declared yet.
If we try the same thing using const
(or let
), we get a different response:
'option strict';
function myFunction() {
console.log(foo);
// => Uncaught ReferenceError: Cannot access 'foo' before initialization
const sentence = 'my,array,of,strings';
const foo = sentence.split(',');
console.log(foo);
// => ['my', 'array', 'of', 'strings']
}
myFunction();
Upvotes: 2