SyntaxPilot
Courses/JavaScript/Lesson 9

JavaScript · Lesson 9 of 40 · 11 min

Functions, arrow functions, default parameters

queued

These are the notes for JavaScript episode 9. You will learn why copy-pasted formulas go out of date, how to declare and call a function, parameters vs arguments, return (and the undefined you get without it), what happens with missing arguments, default parameters, function expressions, arrow functions and implicit return, calling a function before it's defined, TypeError: x is not a function, passing functions as values (callbacks), and pure functions. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

Why functions: the GST change

Ravi's stall now serves lunch too, so his app prints three bills: morning chai, lunch thali and evening snacks. Each bill uses the same rule, amount + amount × GST rate, copy-pasted three times. Then GST goes from 5% to 12%, and Ravi updates the copies he can find:

// morning bill
const chai = 3 * 10;
console.log(`Morning: Rs ${chai + chai * 0.12}`);
// lunch bill
const thali = 2 * 80;
console.log(`Lunch: Rs ${thali + thali * 0.12}`);
// evening bill
const snacks = 4 * 15;
console.log(`Evening: Rs ${snacks + snacks * 0.05}`);
Morning: Rs 33.6
Lunch: Rs 179.2
Evening: Rs 63

The evening bill is still on 5%: every evening customer gets the wrong bill, with no error and no warning. The same rule lives in three copies, every change must be made three times, and you only need to miss one. We need to write the rule once, give it a name, and use the name everywhere. That is a function.

Declaring and calling: a juice machine

A juice machine In JavaScript Name
Build the machine once; the recipe is inside function billWithGst(amount) { ... } declaration (name + body)
The slot where fruit goes in amount parameter
Juice comes out of the spout return amount + gst; return value
Press the button, any fruit, any time billWithGst(30) call, with an argument
function billWithGst(amount) {
  const gst = amount * 0.12;
  return amount + gst;
}
console.log(`Morning: Rs ${billWithGst(30)}`);
console.log(`Lunch: Rs ${billWithGst(160)}`);
console.log(`Evening: Rs ${billWithGst(60)}`);
Morning: Rs 33.6
Lunch: Rs 179.2
Evening: Rs 67.2
  • A function is a named, reusable block of code: the keyword function, a name, parameters in round brackets, and the body in curly brackets.
  • Calling it means writing its name with round brackets: billWithGst(30). The value you pass in (30) is an argument; inside the function, the parameter amount holds it.
  • return hands a value back to the caller, and ends the function immediately.
  • Defining a function runs nothing. The first four lines only build the machine; nothing happens until it's called.
  • If GST changes again, there's exactly one line to update.
 function billWithGst(amount) { return amount * 1.12; }
          └── name ──┘ └param┘   └─── the output ───┘

 billWithGst(30)      // a call: the argument 30 goes into the slot "amount"

Parameter = the slot. Argument = the value you put in it.

Trap 1: forgetting return

function billWithGst(amount) {
  const gst = amount * 0.12;
  amount + gst;
}
const bill = billWithGst(100);
console.log(bill);
undefined

The machine made the juice and poured it down the drain: the function computed amount + gst and threw it away. A function without return gives back undefined. If you want a value out, return it.

Two more return facts:

function check(age) {
  if (age < 18) {
    return "Too young";
  }
  return "Welcome";
  console.log("never runs");
}
console.log(check(15), check(30));
function bill(amount) {
  return
    amount * 1.12;
}
console.log(bill(100));
Too young Welcome
undefined
  • return ends the function: the line after it never runs. An early return is a clean way to handle special cases first.
  • Never put a line break right after return: JavaScript inserts a semicolon there (automatic semicolon insertion), so return returns undefined and the next line is ignored.

Trap 2: missing arguments

function total(price, qty) {
  return price * qty;
}
console.log(total(10, 3));
console.log(total(10));
30
NaN

JavaScript doesn't complain about a missing argument: the parameter qty just becomes undefined, and 10 * undefined is NaN (not a number). Extra arguments are silently ignored: avg(4, 6, 100) with two parameters uses only 4 and 6.

Default parameters

function total(price, qty = 1) {
  return price * qty;
}
console.log(total(10, 3));
console.log(total(10));
function greet(name = "friend") {
  return `Hello, ${name}!`;
}
console.log(greet("Meena"), greet());
30
10
Hello, Meena! Hello, friend!

A default parameter (qty = 1) is used only when that argument is missing (or undefined). Most customers buy one item, so the default makes the common case short.

Function expressions and arrow functions: a full form vs a quick note

A function is a value, like a number or a string, so it can be stored in a variable. That's a function expression. For small jobs, the short form is an arrow function:

Writing it down In JavaScript
The full bank form function (amount) { return amount * 2; }
A sticky note (amount) => amount * 2
One parameter, no brackets needed amount => amount * 2
No parameters () => "Hi!"
const withGst = function (amount) {
  return amount + amount * 0.12;
};
const withGstArrow = (amount) => amount + amount * 0.12;
const double = n => n * 2;
const sayHi = () => "Hi!";
console.log(withGst(100), withGstArrow(100), double(21), sayHi());
112 112 42 Hi!
  • => is made of = and >. Parameters on the left, the job on the right.
  • If the job is a single expression, the arrow returns it automatically: an implicit return.
  • With exactly one parameter you may drop the round brackets; with zero or two or more you need them.

The arrow { } trap

const withGst = (amount) => { amount + amount * 0.12; };
console.log(withGst(100));
undefined

Curly brackets turn the arrow into a full block, and the automatic return switches off. Either remove the braces ((amount) => amount + amount * 0.12) or write return inside them.

Calling before defining

console.log(early(5));
function early(n) {
  return n + 1;
}
console.log(late(5));
const late = (n) => n + 1;
6
ReferenceError: Cannot access 'late' before initialization
Kind Example Usable before its line?
Function declaration function early(n) { ... } yes, ready from the start of the file
Function in a const / let const late = (n) => ... no: ReferenceError

Why? That's hoisting, the topic of episode 10. For now: define const functions before you call them.

TypeError: x is not a function

const discount = 10;
console.log(discount(100));
TypeError: discount is not a function

Round brackets after a name mean call it, and only functions can be called. When you see this error, check the spelling and check what that name really holds (typeof discount is "number"; for a function, typeof says "function").

Functions as values: callbacks

The stall's announcer In JavaScript
One announcer, given a message announce(message, style)
...and told HOW to say it: shout announce("Chai is ready", shout)
...or whisper announce("Chai is ready", whisper)
function shout(text) {
  return text.toUpperCase() + "!";
}
function whisper(text) {
  return text.toLowerCase() + "...";
}
function announce(message, style) {
  console.log(style(message));
}
announce("Chai is ready", shout);
announce("Chai is ready", whisper);
const amounts = [250, 80, 120];
amounts.sort((a, b) => a - b);
console.log(amounts);
CHAI IS READY!
chai is ready...
[ 80, 120, 250 ]
  • Because functions are values, you can pass a function to another function. A function passed in like this is a callback.
  • Pass shout without brackets: you hand over the machine, not its juice. shout() would call it right away.
  • The sort rule from episode 7, (a, b) => a - b, is a callback: sort calls it to compare two items. Callbacks power map, filter and reduce (episode 11) and asynchronous code (episode 25).
  • A function that takes or returns a function is called a higher-order function (announce, sort).

Pure functions

let total = 0;
function addBad(amount) {
  total += amount;
  return total;
}
console.log(addBad(10), addBad(10));
function add(a, b) {
  return a + b;
}
console.log(add(10, 10), add(10, 10));
10 20
20 20

addBad gives a different answer for the same input, because it secretly changes a variable outside itself (a side effect). add only uses its inputs and changes nothing outside: a pure function. Like a calculator, 2 + 2 is always 4. Pure functions are easy to test, easy to reuse and hard to break. Printing with console.log is also a side effect, so keep calculating and printing in separate functions when you can.

Common mistakes (and what really happens)

You wrote What happens Why Fix
function f(a) { a * 2; } (no error) undefined no return return a * 2;
total(10) (needs price, qty) (no error) NaN qty is undefined a default: qty = 1
(a) => { a * 2; } (no error) undefined { } turns off the implicit return (a) => a * 2
late(5); const late = ... ReferenceError: Cannot access 'late' before initialization a const isn't ready before its line define it first
const discount = 10; discount(100); TypeError: discount is not a function only functions can be called check what the name holds
return then a line break (no error) undefined a semicolon is inserted after return keep the value on the same line
announce("Hi", shout()) TypeError: Cannot read properties of undefined (reading 'toUpperCase') shout() ran with no text pass shout without brackets
copy-pasted formulas (no error) some copies out of date the same rule in many places one function

Mini project: a bill calculator

const GST = 0.12;
const PRICES = { chai: 10, samosa: 12, "vada pav": 15 };

const lineCost = (item, qty = 1) => PRICES[item] * qty;
const withGst = (amount) => Math.round(amount * (1 + GST));

function printBill(customer, order) {
  let subtotal = 0;
  for (const item in order) {
    subtotal += lineCost(item, order[item]);
  }
  console.log(`${customer}: Rs ${subtotal} + GST = Rs ${withGst(subtotal)}`);
}
printBill("Asha", { chai: 3, samosa: 2 });
printBill("Meena", { "vada pav": 4 });
printBill("Ravi", { chai: 1 });
Asha: Rs 54 + GST = Rs 60
Meena: Rs 60 + GST = Rs 67
Ravi: Rs 10 + GST = Rs 11
  • The GST rate and the price list live in one place each (constants in capitals are a common convention for fixed settings).
  • lineCost and withGst are small pure arrow functions; lineCost has a default quantity of 1.
  • printBill takes an order object (episode 8) and loops over its keys with for...in.
  • If GST changes tomorrow, you change one number.

Try adding your own customers and items to PRICES.

Practice

  1. Write area(length, width = length) that works for squares and rectangles.
  2. Write isEven(n) as an arrow function.
  3. Write maxOf(a, b) without Math.max.
  4. Write applyTwice(fn, x): applyTwice(n => n + 3, 1) should give 7.
Solutions and hints
function area(length, width = length) {
  return length * width;
}
console.log(area(4), area(4, 6));
const isEven = (n) => n % 2 === 0;
console.log(isEven(10), isEven(7));
function maxOf(a, b) {
  return a > b ? a : b;
}
console.log(maxOf(3, 9), maxOf(12, 5));
const applyTwice = (fn, x) => fn(fn(x));
console.log(applyTwice(n => n + 3, 1));
16 24
true false
9 12
7
  1. A default can use an earlier parameter: width = length makes area(4) a 4 × 4 square.
  2. % is the remainder (episode 3); an even number leaves 0.
  3. The ternary operator (episode 5) picks the bigger one.
  4. fn(fn(x)): 1 + 3 = 4, then 4 + 3 = 7. applyTwice is a higher-order function.

Quick quiz

What does this print?

function f(x = 2) {
  return x * 3;
}
console.log(f() + f(1));
  • A. 3
  • B. 6
  • C. 9
  • D. NaN
Answer

C. f() uses the default x = 2 and returns 6; f(1) returns 3. 6 + 3 = 9.

Interview questions

  • What is a function? Why use functions instead of copy-pasting code?
  • What's the difference between a parameter and an argument?
  • What does a function return if it has no return statement?
  • What happens when you call a function with fewer arguments than parameters? With more?
  • How do default parameters work? When is the default used?
  • What's the difference between a function declaration and a function expression?
  • What is an arrow function? What is an implicit return, and when does it stop working?
  • Why can you call a function declaration before its line, but not a const arrow function?
  • What is a callback? What is a higher-order function? Give an example.
  • What is a pure function? What is a side effect?

Glossary

Term Meaning Example
Function a named, reusable block of code function billWithGst(amount) { ... }
Declaration defining a function with the function keyword function early(n) { ... }
Body the code inside the curly brackets { return amount + gst; }
Call (invoke) running a function: its name + ( ) billWithGst(30)
Parameter an input slot named in the definition amount
Argument the actual value passed in a call 30
return sends a value back and ends the function return amount + gst;
Return value what a call evaluates to billWithGst(100) → 112
undefined what you get with no return, or a missing argument total(10) → qty is undefined
NaN "not a number": a failed calculation 10 * undefined
Default parameter a value used when the argument is missing qty = 1
Function expression a function stored in a variable const f = function (x) { ... };
Arrow function the short form (params) => job (a) => a * 2
Implicit return an arrow with one expression returns it automatically n => n * 2
Hoisting (preview) declarations are ready before their line runs episode 10
ReferenceError using a name that isn't available (yet) Cannot access 'late' before initialization
TypeError using a value the wrong way discount is not a function
First-class functions functions are values you can store and pass announce("Hi", shout)
Callback a function passed to another function to be called later (a, b) => a - b in sort
Higher-order function a function that takes or returns a function announce, sort
Side effect a change outside the function total += amount on an outer variable
Pure function same input → same output, no side effects add(a, b)
Constant (convention) a fixed setting written in capitals const GST = 0.12;

Summary

  • A function is a named job you write once and call anywhere: change the rule in one place and every call is fixed.
  • Parameters are the slots, arguments the values. return gives the result back and ends the function; no return → undefined.
  • A missing argument is undefined (often → NaN); default parameters (qty = 1) fill it.
  • Arrow functions (a) => a * 2 are the short form with an implicit return; add { } and you need return.
  • Function declarations can be called before their line; const functions can't (ReferenceError). Calling a non-function is a TypeError.
  • Functions are values: pass them as callbacks (without brackets). Prefer pure functions.

Next episode: scope, hoisting and closures. Why could we call early before it was defined but not late? Where do a function's variables go when it ends? And how can a function remember things?