Learn JavaScript from Scratch

Functions in JavaScript

Lesson 5 of 9 2 min read Updated 28 September 2026

What is a function?

A function is a reusable block of code that performs a task. You define it once and call it many times.

function greet(name) {
  return "Hello, " + name + "!";
}
console.log(greet("Asha"));   // Hello, Asha!
  • name is a parameter, and "Asha" is an argument.
  • return sends a value back to the caller.

Arrow functions

const add = (a, b) => a + b;
const square = n => n * n;
console.log(add(2, 3), square(4));   // 5 16

Default and rest parameters

function welcome(name = "Guest") {
  return `Welcome, ${name}`;
}
function total(...numbers) {
  return numbers.reduce((sum, n) => sum + n, 0);
}
console.log(welcome(), total(1, 2, 3, 4));

Scope

Variables declared inside a function are not visible outside it.

function test() {
  const secret = 42;
}
// console.log(secret);  // Error: secret is not defined

let and const are also block-scoped, which means they live inside the nearest { }.

Functions as values

<script>
function repeat(times, action) {
  for (let i = 0; i < times; i++) action(i);
}
repeat(3, i => document.write("Run number " + (i + 1) + "<br>"));
</script>

Functions can be passed to other functions. This idea, called a callback, is used everywhere in JavaScript.

Good practice

  • Give functions clear verb names such as calculateTotal.
  • Keep each function focused on one job.
  • Avoid changing global variables inside functions.

Practice

Write a function isPrime(n) that returns true for prime numbers, and use it to print all primes up to 50.