var text = \'outside\';
function logIt(){
console.log(text);
text =\'inside\';
}
logIt(); //prints outside. why?
I thought the
Hoisting: You can understand it as Entire function body is taken at the top of the script along with variables which have a value of undefined (if using them before assignment is done)
Now Case1:
At the time when you are calling the function and the console.log executes the value of text is still "outside"
And after console log it changes value to "inside"
If you write console.log immediately after calling logIt(), it will display "inside" then.
var text = 'outside';
function logIt(){
console.log(text);
text ='inside';
}
logIt(); //prints outside. why?
Case 2: In this case you are making a new var inside the function logIt which will then be hoisted as var text = undefined (as you are using it before assignment)
var text = 'outside';
function logIt(){
console.log(text);
var text ='inside';
}
logIt(); //prints undefined
Try printing console.log(text) after calling function this time. It will print "outside in this case as global scope has no effect because of logIt function in this case"