JavaScript Functions Explained for Beginners: Complete Guide

JavaScript Functions Explained for Beginners: Complete Guide

A function is a reusable block of code with a name. You write the steps once, then run them whenever you need them. JavaScript functions are everywhere: a button click, a price calculation, a request to a server. Learn them well and the rest of JavaScript falls into place much faster.

This guide starts with the simplest function and builds up to arrow functions and callbacks, with output shown for every example. You should be comfortable with variables and data types before you begin.

Your first function

Here is a function declaration. It has a name, a list of inputs in parentheses, and a body in curly braces.

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

console.log(greet("Asha")); // Hello, Asha!
console.log(greet("Ravi")); // Hello, Ravi!

Defining the function does nothing by itself. It runs only when you call it by writing its name followed by parentheses. The same code gives different results because the input changes.

Parameters and arguments

People mix these two words up, and it rarely causes harm, but here is the difference. Parameters are the names listed in the definition. Arguments are the actual values you pass when you call it. In greet("Asha"), name is the parameter and "Asha" is the argument.

Default values

If a caller leaves out an argument, the parameter is undefined. A default value gives you a safe fallback.

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

console.log(greet());        // Hello, friend!
console.log(greet("Meera")); // Hello, Meera!

Any number of arguments

The rest syntax (...) collects extra arguments into an array.

function sum(...numbers) {
  let total = 0;
  for (const n of numbers) total += n;
  return total;
}

console.log(sum(2, 3, 5)); // 10

If arrays are new to you, our JS arrays guide explains how to work with the list that numbers holds.

Return values

The return keyword hands a result back to whoever called the function and stops the function immediately. A function with no return gives back undefined.

function isAdult(age) {
  if (age >= 18) return true;
  return false; // only reached when the check above fails
}

console.log(isAdult(20)); // true
console.log(isAdult(12)); // false

A common beginner mix-up is using console.log inside a function instead of return. Logging only prints something to the console. Returning lets you store the result in a variable and use it again.

Related reading: JS Scope and Hoisting Explained for Beginners

Three ways to write a function

JavaScript gives you more than one syntax. They look different, but they all create functions.

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

// 2. Expression (a function stored in a variable)
const subtract = function (a, b) { return a - b; };

// 3. Arrow function
const multiply = (a, b) => a * b;

console.log(add(4, 2), subtract(4, 2), multiply(4, 2)); // 6 2 8

Which should you use? Declarations are easy to read and can be called before the line where they are written, because of hoisting. Arrow functions are shorter and popular for small inline helpers. Arrow functions came with ES6, along with template strings and default parameters, which you have already seen above.

One difference worth remembering: arrow functions do not have their own this. That is useful in some situations and confusing in others, so beginners can safely use regular functions as methods on objects until they are comfortable.

Here is what hoisting means in practice. A declaration works even when you call it above its definition, but an arrow function stored in a const does not:

console.log(double(4)); // 8, declarations are hoisted

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

// console.log(triple(4)); // would throw ReferenceError
const triple = (n) => n * 3;
console.log(triple(4)); // 12

Functions are values

In JavaScript you can pass a function to another function, just like a number or a string. The function you pass is called a callback.

const prices = [100, 250, 80];

// map runs our small function on every item
const doubled = prices.map((p) => p * 2);

console.log(doubled); // [ 200, 500, 160 ]

The same idea powers event handlers, timers and requests to servers. A function that takes or returns another function is called a higher-order function, which sounds fancy but is just the pattern above.

Scope: what a function can see

Variables created inside a function live only inside it. Code outside cannot see them, but the function can see variables from the outside.

const city = "Pune"; // visible everywhere

function describe() {
  const mood = "sunny"; // visible only in here
  return `${city} is ${mood} today`;
}

console.log(describe()); // Pune is sunny today
// console.log(mood);    // would throw ReferenceError

Keeping variables local prevents different parts of your program from stepping on each other. A function can also remember its surroundings after it returns, which is the idea behind closures.

Tips for writing good functions

  • Do one job. If you need "and" to describe what a function does, split it in two.
  • Use verb names. calculateTotal and isValidEmail tell you what to expect.
  • Prefer returning values over changing outside variables, so results are easy to predict and test.
  • Keep parameters few. Three or four is a comfortable limit; beyond that, pass a single object.

Common mistakes

  • Writing greet instead of greet(). Without parentheses you reference the function but never run it.
  • Forgetting return and then wondering why the result is undefined.
  • Putting the return value on a new line after return, which makes JavaScript return nothing.
  • Using a variable declared inside a function from outside it.

Practice by rewriting small tasks as functions, then explore more in the JavaScript category.

Conclusion

You now know the core of how functions work. To recap:

  • A function is a named, reusable block of code that runs when called.
  • Parameters are names in the definition; arguments are the values you pass.
  • Use return to send a result back; without it you get undefined.
  • Declarations, expressions and arrow functions are three ways to write the same idea.
  • Functions are values, so you can pass them around as callbacks.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Your comment will appear after moderation.