Learn JavaScript from Scratch, Part 5: Functions

Learn JavaScript from Scratch, Part 5: Functions - CodingHumans

Functions are the single most important idea in JavaScript: named, reusable blocks of code you can run whenever you want. Every click handler, every array method, every React component is a function. In this part of learn JavaScript from scratch you'll write them three ways and understand parameters, return, and callbacks.

This is Part 5 of Learn JavaScript from Scratch, continuing from Part 4.

1. What a function is

function greet(name) {
  return `Hello, ${name}!`;
}
const message = greet("Asha");   // "Hello, Asha!"
greet("Ravi");                   // call it as often as you like

Define once, call many times. The win isn't just less typing — it's one place to fix. If the greeting changes, you edit one function instead of fifty copies. Two terms you'll hear constantly: parameters are the named slots in the definition (name); arguments are the actual values you pass when calling ("Asha").

2. Three ways to write a function

// 1. Function declaration
function add(a, b) { return a + b; }

// 2. Function expression - stored in a variable
const add2 = function (a, b) { return a + b; };

// 3. Arrow function - the modern short form
const add3 = (a, b) => a + b;

All three are called the same way: add(2, 3). Differences that matter now:

FormKey property
DeclarationHoisted - usable even before the line it's defined on (Part 13)
ExpressionExists only after that line runs
ArrowShortest; no braces + no return needed for a single expression; treats this differently (Part 15)

Arrow shorthand rules: one parameter can drop its parentheses, n => n * 2; with braces you're back to needing return:

const double = n => n * 2;            // implicit return
const double2 = n => { return n * 2; };  // explicit - same thing

3. Parameters: defaults and rest

function greet(name = "Guest") {
  return `Hello, ${name}!`;
}
greet();          // "Hello, Guest!" - default used
greet("Asha");    // "Hello, Asha!"

Call a function with a missing argument and that parameter is undefined — defaults catch exactly that case. Extra arguments are ignored. And when you genuinely want "any number of arguments", the rest parameter collects them into an array:

function sum(...numbers) {          // numbers is a real array
  let total = 0;
  for (const n of numbers) total += n;
  return total;
}
sum(1, 2, 3, 4);   // 10

4. return - the exit door

  • return value hands a result back to the caller and stops the function immediately. Code after it never runs.
  • A function with no return (or a bare return;) gives back undefined.
  • console.log shows a value; return hands it back so other code can use it. Mixing these up is the #1 beginner confusion: a function that only logs can't feed its result into a calculation.

Early returns keep code flat and readable:

function canVote(age) {
  if (age < 18) return false;   // handled - exit now
  return true;                  // no else needed
}

5. Functions are values: callbacks

Here's the idea that unlocks all of modern JavaScript: a function is a value, like 42 or "hello". You can store it, pass it to another function, and have that function call it later. A function passed in to be called later is a callback:

function processOrder(order, onDone) {
  console.log("Processing", order);
  onDone();                        // call the callback
}
processOrder("#124", () => console.log("Done!"));

You've already met this shape: setTimeout(() => ..., 1000) passes a callback for the browser to run later, and array methods like forEach (next part) take a callback to run per element. One trap: pass the function itself, don't call it on the spot:

setTimeout(sayHi, 1000);     // right: hands over the function
setTimeout(sayHi(), 1000);   // wrong: runs sayHi NOW, hands over its return value

6. Common mistakes

  • Logging instead of returning — then wondering why result is undefined.
  • Calling instead of passing a callback (the sayHi() trap above).
  • Dead code after return — anything below a top-level return in the same block never runs.
  • One function doing five jobs. Aim for one clear task per function with a name that says it: calculateTotal, isValidEmail.
Interview note: "declaration vs expression vs arrow" is a standard question — the full answer adds hoisting (Part 13) and this (Part 15). We're building it layer by layer on purpose.

Practice: test what you learned

Q1. What does this print? function f(){ return 5; console.log("after"); } console.log(f());

a) after then 5

b) 5 only - the log after return never runs

c) after only

d) 5 then after

Q2. What is the value of x? function hi(){ console.log("hi"); } const x = hi();

a) "hi"

b) The function hi itself

c) undefined

d) null

Q3. Which arrow function correctly doubles a number?

a) const d = n => n * 2;

b) const d = n => { n * 2 };

c) const d = (n) => return n * 2;

d) const d = n =>> n * 2;

Q4. greet("Asha", "extra", 42) is called on function greet(name){...}. What happens?

a) A TypeError about too many arguments

b) Only "extra" is used

c) The call is ignored

d) It runs normally; the extra arguments are ignored

Q5. Which line passes a callback correctly to run after 1 second?

a) setTimeout(ring(), 1000)

b) setTimeout(ring, 1000)

c) setTimeout("ring", 1000)

d) setTimeout => ring(1000)

Q6. What does function sum(...nums) make nums inside the function?

a) A string of the arguments

b) The first argument only

c) A real array of all passed arguments

d) An object with named keys

FAQ

Should I always use arrow functions?

For short callbacks and most everyday code, yes - they are concise. Classic declarations still shine for top-level named functions, and the real decision point is this-binding, which we cover in Part 15.

What happens if I call a function with fewer arguments than parameters?

Missing parameters are undefined. Give them defaults (name = "Guest") when a sensible fallback exists.

Can a function return more than one value?

Not directly - but it can return an array or object holding several values, and destructuring (Part 9) unpacks them neatly on the other side.

What exactly is a callback?

A function you pass to another function so IT can call it at the right moment - after a timer, per array element, when data arrives. It is the foundation of async JavaScript in Part 18.

Learning with others? Join the CodingHumans WhatsApp community to get each new part of Learn JavaScript as soon as it goes live.

Comments

Answered 0/0Correct 0