NEBians
search Sign In Register

Functions in Action

Lesson 2 of 3 Coding game schedule20 min

Loading simulation…

sports_esportsPlay with the blocks and run your code

flagWhat you'll discover

  • arrow_forwardDefine functions with parameters and return values
  • arrow_forwardUnderstand the difference between returning and printing
  • arrow_forwardWrite code that passes hidden automated tests
  • arrow_forwardReuse one function for many different inputs

Functions are machines you build

A function is a reusable machine: values go in through parameters, something comes out through return. function double(n) { return n * 2; } builds a machine named double; calling double(4) feeds in 4 and gets back 8. Define once, use forever — with any input. This is the heart of programming: instead of repeating logic everywhere, you build a well-named machine and call it. Big apps are thousands of small functions calling each other, each doing one job well.

Return is not print

console.log shows a value to humans; return hands a value back to the code that called the function. Only return lets results flow onward: console.log(double(5) + 1) works because double returns 10, which becomes 11. A function that only logs is a dead end — nothing can use what it computed. The hidden tests in this lesson call your functions and inspect the returned values, so a function that prints instead of returning will fail even though the right number appears on screen!

Tests prove code works

When you press Run, Neby quietly appends extra calls to your code — double(4), double(9.5), greet("Mina"), greet("Ramesh") — and checks the answers. This is automated testing, and it is how serious software is built: every major app runs thousands of automatic tests before each update ships. Notice the trick of testing with several different inputs: code that only works for one special value is not really working. If a hidden test fails, ask: what input might my function handle wrongly?

quizCheck your knowledge

1. What does function double(n) { return n * 2; } then double(8) give?
2. Why is return better than console.log inside a function?
3. Why do tests try your function with several different values?