Is this the correct understanding of call site and call stack?
Call-site is where the function is called.
Call-stack is the order that the function is called.
function baz() {
// call-stack is: `baz`
// so, our call-site is in the global scope
console.log( "baz" );
bar(); // <-- call-site for `bar`
}
function bar() {
// call-stack is: `baz` -> `bar`
// so, our call-site is in `baz`
console.log( "bar" );
foo(); // <-- call-site for `foo`
}
function foo() {
// call-stack is: `baz` -> `bar` -> `foo`
// so, our call-site is in `bar`
console.log( "foo" );
}
baz(); // <-- call-site for `baz`
- In this code snippet, the 1st function call is
baz()
, then baz
called bar
, bar
called foo
. So the call stack is baz==>bar==>foo
Is this correct? then why there are 2 call site for baz()
? one is
// call-stack is: baz
// so, our call-site is in the global scope
the other one is:
baz(); // <-- call-site for baz
Iām confusedā¦
Never heard of call-site, but the second one seems to be the call-site. In the first comment it says that the call-site is the global scope, because baz() is inside global scope.
yeah thatās what confuses me.
I found some of the explanations in YDKJS series is quite confusing.
In the second snippet (which says baz(); // <-- call-site for baz), baz is in the global scope. That is to say, itās not called within a function or within another thing that has itās own scope. So thereās not two call-sites for baz.
I see. Thanks !! (20 character limits)
The comments are technically right, but I can see why it seems confusing.
In the last line, you call baz
from the global scope ā thatās the call site. Assuming your environment is a browser, you would call baz
on the global window
object ā window.baz()
, given that window is the global scope. baz()
is just the implicit way for saying that.
Calling baz() makes the engine push baz() onto the call stack. This is why, when youāre executing function baz()
, call stack is just ābazā. The following comment, āso our call site is in the global scopeā is the confusing bit. Itās really just reminding you that you called baz
down at the bottom from the global scope.
1 Like
I see. Thanks! I m new to js so just try to understand all these.