Question 19 / 31

Why does the last line print nothing?

Topic: this bindingDifficulty: Intermediate

call and apply invoke the function immediately with a supplied this; bind only returns a new function.

Solve it with the execution visualizerStep through every binding, function call, and console output below.

Predict the output

Predict the output. All four lines call foo — or do they? Count how many console.log lines actually appear.

function foo() {
  console.log(this.a);
}
var obj = { a: 1 };
var a = 2;

foo();
foo.call(obj);
foo.apply(obj);
foo.bind(obj);
Reveal the answer and explanation

Expected output

2
1
1

Why this happens

foo() is a receiver-less call, so default binding applies: this is the global object, and this.a reads the global var a, which is 2.

foo.call(obj) and foo.apply(obj) both perform explicit binding — they invoke foo immediately with this forced to obj, so this.a reads 1 both times.

foo.bind(obj) does not invoke foo at all. It synchronously returns a brand-new bound function with obj permanently attached as its this. Because that returned function is never called, foo's body never runs a fourth time and nothing is logged for that line.

What this question tests

  • call and apply invoke the function immediately with an explicit this
  • bind returns a new function instead of calling the original
  • a bound function's this cannot be overridden by a later call, apply, or bind

Runtime assumptions

Assumes a classic sloppy-mode script, where default binding resolves to the global object instead of undefined.

Specification references

JavaScript Code EditorDirectly edit or paste custom code
Step 0 of 0
StepSpaceRun
Press → (Step) or Space (Run)
Phase 1: Compilation(Hoisting & Memory Setup)
Phase 2: Execution(Line-by-line Evaluation)
Execution Step Breakdown

Press "→" / click "▶" to step line-by-line, or press "Space" / click "▶ Run" for auto-play.