0

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?

2
  • it happens in chronological order Commented Oct 28, 2016 at 4:17
  • Here's a useful video Commented Oct 28, 2016 at 4:19

1 Answer 1

1

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").

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.