I have a very simple Javascript code, can't fully understand the running order and output.
function f1() {
n = 999;
change = function() {
n = "Barry";
};
return change;
}
var result = f1();
result();
console.log(n)
change();
console.log(n)
Output:
Barry
Barry
As my understand, I define a globale variable n, and n = 999. Then I create a function which will define globale n to "Barry". and assign this function to change. and return this change variable.
Then I trigger this f1(), and give change to result. At this timepoint the change is a function but not runs yet.
So why the first Console.log return my Barry? Then change has not runs yet..
You are not properly declaring your variables in the scope with either var, let or const so it is polluting the global or outer scopes.
n is changed because result === change and change sets n to Barry.
The reason for this behavior is at this line ,
var result = f1(); // n - 999
At this point you are calling the inner function and setting the n to Barry
result(); // n - Barry
I am not sure how you calling this function directly. But hope it's just a pseudo code
change(); // n - Barry
Which means,
result() === change()
why the first Console.log return my Barry? Then change has not runs yet..
Yes it has, you are only calling console.log after having called result(). Try the following:
var n, change;
function f1() {
n = 999;
change = function() {
n = "Barry";
};
return change;
}
console.log(n);
var result = f1();
console.log(result === change);
console.log(n);
result();
console.log(n);
change();
console.log(n);