Reputation: 29
I can't grasp the result. I understand the first two sets of output (func01 1 and func2 01 - func2 05). But the rest is confusing.
My understanding is that, after the first execution of the for loop in func01()
, i gets to 2 and then 3 because of the function func02()
, but still i <= 3 in func01()
. I don't know why there isn't func01 2 and func01 3 in the output .
function func02(){
for (i = 1; i <= 5; i++){
document.write(" func02 " + i + "<br>");
}
}
function func01(){
for(i = 1; i <= 3; i++){
document.write("func01 " + i + "<br>");
func02();
}
}
func01();
Upvotes: 0
Views: 86
Reputation: 581
user202729 is right. In javascript, if you do not declare a variable, it takes global scope, instead of taking the function's scope in which that variable is used.
Declare your variable i, as follows ,
for(var i = 1;i <= 5 ; i++)
or you can declare the variable at the beginning of the function like,
var i;
function func02(){
for (var i = 1; i <= 5; i++){
document.write(" func02 " + i + "<br>");
}
}
function func01(){
for(var i = 1; i <= 3; i++){
document.write("func01 " + i + "<br>");
func02();
}
}
func01();
Do refer https://www.w3schools.com/js/js_scope.asp and lookup about the scoping of javascript variables.
Upvotes: 0
Reputation: 4703
When you assign a variable without using var
, and it doesn't exist anywhere in the current scope, it's looked for in the next scope up. If it's not there, the next scope up is checked, etc.
If the variable is not found in any scope, it gets assigned to the global scope. So both func01
and func01
are referring to and updating the same i
variable. So func02
runs, loops, and finishes. Then by the time it gets to func01
, i
is 6
and the loop doesn't run again in func0
.
You can get the expected result if you change the counters to use var
. That will scope i
to the functions they're inside of.
function func02(){
for (var i = 1; i <= 5; i++){
document.write(" func02 " + i + "<br>");
}
}
function func01(){
for(var i = 1; i <= 3; i++){
document.write("func01 " + i + "<br>");
func02();
}
}
func01();
Upvotes: 1
Reputation: 44087
You haven't defined i
as a local scopes variable, so it's being created as a global variable. Use let
or var
:
function func02(){
for (i = 1; i <= 5; i++){
document.write(" func02 " + i + "<br>");
}
}
function func01(){
for(i = 1; i <= 3; i++){
document.write("func01 " + i + "<br>");
func02();
}
}
func01();
Upvotes: 0
Reputation: 1420
This is the result I got (formatted)
func01 1
func02 1
func02 2
func02 3
func02 4
func02 5
func01
is called, sets i (which is global variable) to 1, and prints a line
Then func01
calls func02
func02
resets i to 1, and then prints a line for each i=1,2,3,4,5
.
Then control returns to func01
. It has completed the first loop iteration. The value of i is 5. It then compares i (as its global variable) to 3. Seeing that 5 is greater, the loop is over.
Upvotes: 1