user502019
user502019

Reputation: 49

Return values in javascript

I have been programming for 5 years but I just started wondering something. In this code example, I return a value from a function and store it a variable. In what order does this happen? Does it matter whether the language is interpreted or compiled?

function foo() {
    return "junk";
}

var bar = foo();

Now I know bar = "junk". In what order does this take place? I know when a function is called it returns the control back to the function invoking it and the program resumes where it left off, so does that mean it returns back to 'var bar =' ?

And in a dynamically typed language, how is bar initially created? Is it created on the heap?

Upvotes: 0

Views: 54

Answers (1)

Pavan Chandaka
Pavan Chandaka

Reputation: 12731

All function calls in javascript are executed as stack of frames.

In your case, when "foo" call occurs, a stack frame is created for entire "foo" function call, and that frame contains, all foo's variables and their information.

If another function is called in foo, then another stack frame is created for that function.

You know stack behavior right, the last in comes out first. Here the function inside foo (if exists) executes first and gets out of the stack. and the next turn is "foo".

Then "foo" executes and comes out of the stack and now the variable turn comes (in your case it is "bar").

Upvotes: 1

Related Questions