LightMySky

Return Values and Variable Scope

Sending a result back out of a function, and the rule that a name created inside a function does not exist outside it.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Return a value and store it in a variable where the call happened
  • Explain why a variable made inside a function cannot be printed after it ends
  • Tell apart a function that prints from a function that returns

1 · Read

A return sends a value back to the caller for later use. calcScore takes a count correct and returns the score, so sallyScore = calcScore(27) stores 90. Print only shows, return delivers.

Try it together

Returned values plug into bigger expressions, like printing Sally earned: beside calcScore(27). Built-ins work the same way: Math.max picks the bigger of two numbers, and substr slices Harry out of Harry Potter. Each hands something back.

Return ends the function on the spot, so put it last. In calcLineSlope the return sits above the slope maths, which never runs and hands back an undefined value. Code after a return is dead.

Good to know

Names made inside a call vanish when it ends, so share data through returns instead. Take inputs in, send outputs out, and your pieces stay predictable.

Return answers to the caller, keep returns last, and let locals live and die inside their call.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Return Values and Variable Scope · Computing, ages 15 to 16 · LightMySky