edubun 한국어

Functions

Write function square(n) { return n * n; } once, and square(4) gives 16, square(9) gives 81, and so on for any number you pass in.

Naming a piece of work

You have already used functions written by other people: console.log, Math.round and toUpperCase are all functions. A function is a named block of code that does one job. You define it once and then call it, by name, as many times as you like. Functions let you avoid copying the same lines around, and they let you think about a program in larger pieces: "calculate the tip, then split the bill" instead of a long list of arithmetic.

function greet(name) {
  return "Hello, " + name + "!";
}

console.log(greet("Ana"));   // Hello, Ana!
console.log(greet("Ji"));    // Hello, Ji!

The definition starts with the keyword function, then the function's name, then a list of parameters in parentheses. A parameter is a variable that receives a value when the function is called; here it is name. The body in curly braces does the work. When you call greet("Ana"), the value "Ana", called an argument, is placed into the parameter name, and the body runs.

return hands back a value

The keyword return ends the function and sends a value back to wherever the function was called. The call greet("Ana") is an expression, and its value is whatever was returned. That is why it can sit inside console.log, or inside a calculation, or be stored in a variable: const msg = greet("Ana");.

Returning a value and printing it are different things, and beginners often mix them up. A function that only calls console.log shows something on the screen, but hands nothing back. Its call evaluates to undefined, so you cannot use the result in a calculation. As a rule, let functions return results and let the code that calls them decide whether to print.

function addPrint(a, b) {
  console.log(a + b);
}
function add(a, b) {
  return a + b;
}

const x = add(2, 3) * 10;
console.log(x);      // 50
addPrint(2, 3);      // prints 5, but returns nothing usable

return also stops the function straight away. Any lines after it in the same path do not run. This lets you handle special cases early: if (n < 0) return "negative"; at the top of a function, with the normal case written below.

Several parameters and default values

A function can take several parameters, separated by commas, and the arguments are matched in order: in add(2, 3), a is 2 and b is 3. If a call leaves out an argument, that parameter is undefined. You can give a parameter a default value that is used when nothing is passed: function tip(bill, rate = 0.15) uses 0.15 unless the caller supplies another rate.

Arrow functions

Modern JavaScript also has a shorter way to write small functions, the arrow function. const square = (n) => n * n; means the same as the square function in the lead. When the body is a single expression, its value is returned automatically, with no braces and no return keyword. You will see arrow functions everywhere in modern code.

Variables inside stay inside

Parameters and variables declared inside a function exist only inside it. This is called scope. Two different functions can each have a variable called total without interfering, and code outside a function cannot see its private variables. A function can read variables declared outside it, but the cleanest functions get everything they need through parameters and give back everything through return, so you can understand them on their own.

function name(parameter) { return result; } const name = (parameter) => result;

functionA named block of code that does one job
callRunning a function: name(arguments)
parameterA variable in the definition that receives a value
argumentThe value passed in a call
returnEnds the function and hands back a value
default parameterrate = 0.15: used when no argument is given
arrow function(n) => n * n
scopeWhere a variable can be seen; inside a function stays inside
  1. What does this print?
    function double(n) {
      return n * 2;
    }
    console.log(double(7));
  2. What does this print?
    function add(a, b) {
      return a + b;
    }
    console.log(add(2, 3) * add(1, 1));
  3. What does this print?
    function minus(a, b) {
      return a - b;
    }
    console.log(minus(3, 10));
  4. What does this print?
    function f(x) {
      return x + 1;
      console.log("hi");
    }
    console.log(f(1));
    • 2
    • hi, then 2
    • 2, then hi
  5. What does this print?
    function show(n) {
      console.log(n);
    }
    const r = show(5);
    console.log(typeof r);
    • 5, then number
    • 5, then undefined
    • Only undefined
  6. What does this print?
    const triple = (n) => n * 3;
    console.log(triple(4));
  7. What does this print?
    function tip(bill, rate = 0.1) {
      return bill * rate;
    }
    console.log(tip(50));
  8. What does this print?
    function tip(bill, rate = 0.1) {
      return bill * rate;
    }
    console.log(tip(50, 0.2));
  9. What does this print?
    function sign(n) {
      if (n < 0) return "neg";
      if (n === 0) return "zero";
      return "pos";
    }
    console.log(sign(0));
  10. In function area(w, h) called as area(3, 5), what are w and h called, and what are 3 and 5 called?
    • w and h are parameters; 3 and 5 are arguments
    • w and h are arguments; 3 and 5 are parameters
    • All four are return values
Key points
  • function name(params) { ... } defines; name(args) calls.
  • Arguments are matched to parameters in order.
  • return ends the function and hands back a value; printing is not returning.
  • Default parameters fill in missing arguments.
  • Arrow functions: (n) => n * n.
  • Variables inside a function stay inside (scope).