0

My head is spinning, can someone please explain how javascript stores variables and what is "Execution context" and "the execution context object"?

Why does the code snippet prints following output on console:

the hello argument

the hello argument

var hello = 'hello is assigned';

function prison(hello) {
  console.log(hello);
  var hello;
  console.log(hello);
}
prison('the hello argument');

Thanks!

2 Answers 2

2

This has less to do with execution context and everything to do with function variable scope. You're passing in 'the hello argument' as an argument to the function and being local it is used instead of the hello var declared outside of the the function.

The var hello does nothing and if you were using use strict or a linter would probably raise a warning (trying to declare an existing variable).

If you changed it to var hello = null; you would see a change to the output.

Now, if you had the following code:

var hello = 'hello is assigned';

function prison() {
  console.log(hello);
  var hello;
  console.log(hello);
}

prison();

...you would get undefined for both logs. This would be due to variable hoisting - variable declarations are moved to the start of a function before execution - so the code would actually appear like so:

function prison() {
  var hello;
  console.log(hello);
  console.log(hello);
}

hello is undefined in both cases.

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

Comments

1

your function prison() has closure over variable hello , the var hello; in prison() is not creating a new variable , the function can see that there is already a global variable hello defined so it uses that variable and hence you get 2 the hello argument

if however ,there was no hello defined before prison() you would get 2 undefined bcoz the definition of hello would be hoisted in prison() and hello has no value set to it.

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.