Syncing account progress…

Back

Intermediate · 12 min

Scope and callbacks

Understand where a variable is visible and pass behavior into a function.

Respect block scope

let and const are scoped to their enclosing block. An inner declaration can use the same name without changing the outer variable.

const label = "Outside";
if (true) {
  const label = "Inside";
  console.log(label);
}
console.log(label);

Output

Inside
Outside

Pass a function

A callback is a function passed to another function. It can read variables from the scope where it was created. Passing a function is different from calling it immediately.

const fee = 2;
function calculate(value, operation) { return operation(value); }
console.log(calculate(10, value => value + fee));

Output

12

Put it into practice

  1. Predict each result before running the example.
  2. Complete the coding task, then explain why your solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Apply a fee

Pass a callback that adds fee to the value and store the result in total. Display total.

Practice