Labs ICT
Pro Login

Functions

5 min read | JavaScript Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

What Is a Function?

A function is a reusable block of code that does a specific task. You give it a name, optionally some input (parameters), and it gives you output (a return value). Functions are how you avoid writing the same code twice.

Think of a function like a recipe. The ingredients are your parameters. The instructions are your code. The finished dish is your return value. You can follow the same recipe as many times as you want with different ingredients.

Function Declaration

A function declaration defines a named function. It is hoisted, meaning you can call it before it appears in the code.

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

console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob"));   // Hello, Bob!

Because declarations are hoisted, this works fine:

console.log(double(5)); // 10 — called before the declaration

function double(n) {
  return n * 2;
}

Function Expression

A function expression assigns a function to a variable. These are not hoisted, so you must define them before calling them.

const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 3)); // 12

Function expressions are useful when you want to pass a function as an argument or assign it conditionally.

Arrow Functions

Arrow functions are a shorter way to write functions. They are especially popular in modern JavaScript.

// Traditional
function add(a, b) {
  return a + b;
}

// Arrow function
const addArrow = (a, b) => a + b;

console.log(add(2, 3));      // 5
console.log(addArrow(2, 3)); // 5

For a single parameter, you can skip the parentheses:

const double = n => n * 2;
console.log(double(5)); // 10

For multiple lines, use curly braces and an explicit return:

const processUser = (name, age) => {
  const status = age >= 18 ? "adult" : "minor";
  return `${name} is ${status}`;
};

console.log(processUser("Alice", 25)); // Alice is adult

Arrow functions are not just shorter syntax. They also handle the this keyword differently — they inherit this from the surrounding code instead of getting their own. This makes them ideal for callbacks.

Parameters and Arguments

Parameters are the names listed in the function definition. Arguments are the actual values you pass when calling the function.

// name and age are parameters
function introduce(name, age) {
  return `I'm ${name} and I'm ${age} years old`;
}

// "Alice" and 25 are arguments
console.log(introduce("Alice", 25));

JavaScript does not complain if you pass more or fewer arguments than parameters. Missing arguments become undefined.

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet()); // Hello, undefined!

Default Parameters

You can set default values for parameters. If the caller does not provide a value, the default is used.

function greet(name = "stranger") {
  return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Hello, Alice!
console.log(greet());         // Hello, stranger!

Return Values

A function returns a value using the return keyword. If there is no return, the function returns undefined.

function add(a, b) {
  return a + b;
}

function logMessage(msg) {
  console.log(msg);
  // no return — returns undefined
}

const sum = add(2, 3);
console.log(sum); // 5

const result = logMessage("hello");
console.log(result); // undefined

You can only return one value. To return multiple values, return an object or an array:

function getUser() {
  return { name: "Alice", age: 25 };
}

const { name, age } = getUser();
console.log(name); // Alice

Rest Parameters

Rest parameters let a function accept any number of arguments as an array.

function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3));       // 6
console.log(sum(10, 20, 30, 40)); // 100

Functions as Arguments (Callbacks)

Functions are values. You can pass them as arguments to other functions. This is the foundation of callbacks, event handlers, and async programming.

function doMath(a, b, operation) {
  return operation(a, b);
}

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

console.log(doMath(10, 5, add));      // 15
console.log(doMath(10, 5, subtract)); // 5

You see this pattern everywhere in JavaScript:

const numbers = [1, 2, 3, 4, 5];

// map, filter, and forEach all take callback functions
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
numbers.forEach(n => console.log(n));

IIFE (Immediately Invoked Function Expression)

An IIFE runs as soon as it is defined, creating a private scope.

(function() {
  const secret = "This is private";
  console.log(secret);
})();
// secret is not accessible outside

IIFEs were common before modules existed. You will still see them in older codebases.

Common Mistakes

  • Forgetting to return — If your function should produce a result, make sure you use return. Without it, you get undefined.
  • Using arrow functions for object methods — Arrow functions do not have their own this, so they break when used as object methods.
  • Not handling missing arguments — Use default parameters to avoid undefined surprises.
  • Writing functions that are too long — If a function does more than one thing, split it into smaller functions.