How to Use Functions in JavaScript

Formulas & functions · Updated November 22, 2026

Functions are reusable blocks of code that perform a specific task. They help you avoid repetition, organize your code, and make it easier to read and maintain. This guide shows you how to define, call, and work with functions in JavaScript, covering function declarations, expressions, arrow functions, parameters, return values, and common pitfalls.

What You’ll Need

  • A text editor (like VS Code, Notepad++, or Sublime Text).
  • A web browser (Chrome, Firefox, Edge, etc.) with developer tools (usually opened with F12).
  • Basic familiarity with JavaScript syntax (variables and data types).

Step-by-Step

  1. Understand the basic function declaration. A function declaration starts with the keyword function, followed by a name, parentheses for parameters, and a block of code in curly braces. For example:
    function greet() {
      console.log("Hello!");
    }

    This defines a function named greet that logs “Hello!” to the console. The code inside does not run until you call the function.

  2. Call the function. To execute the code, write the function name followed by parentheses. Add this after the declaration:
    greet(); // Output: Hello!

    You can call a function as many times as you want.

  3. Add parameters and arguments. Parameters are placeholders in the function definition; arguments are the actual values you pass when calling. For example:
    function greetPerson(name) {
      console.log("Hello, " + name + "!");
    }
    greetPerson("Alice"); // Output: Hello, Alice!

    You can have multiple parameters separated by commas: function add(a, b) {...}.

  4. Return a value. Use the return statement to send a value back to the caller. Once return is executed, the function stops. Example:
    function add(a, b) {
      return a + b;
    }
    let sum = add(5, 3); // sum is 8

    If you don’t return anything, the function returns undefined.

  5. Use function expressions. You can assign a function to a variable. This is called a function expression. The function can be anonymous (no name) or named. Example:
    const multiply = function(a, b) {
      return a * b;
    };
    console.log(multiply(4, 5)); // 20

    Note the semicolon after the closing brace—it’s part of the variable assignment.

  6. Try arrow functions (ES6). Arrow functions provide a shorter syntax and do not have their own this (they inherit it from the surrounding scope). Basic syntax:
    const divide = (a, b) => a / b;
    console.log(divide(10, 2)); // 5

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

    const multiplyAndLog = (a, b) => {
      const result = a * b;
      console.log(result);
      return result;
    };
  7. Understand default parameters. You can set default values for parameters, used when the argument is undefined. Example:
    function greet(name = "Guest") {
      console.log("Hello, " + name + "!");
    }
    greet(); // Hello, Guest!
    greet("Bob"); // Hello, Bob!
  8. Use rest parameters. To accept an indefinite number of arguments, use the rest parameter syntax (...). It collects all remaining arguments into an array. Example:
    function sumAll(...numbers) {
      let total = 0;
      for (let num of numbers) {
        total += num;
      }
      return total;
    }
    console.log(sumAll(1, 2, 3)); // 6
  9. Understand scope. Variables declared inside a function are local to that function (with let or const). They are not accessible outside. Variables declared outside are global and can be accessed inside, but it’s best to avoid modifying globals.
    let globalVar = "I'm global";
    function test() {
      let localVar = "I'm local";
      console.log(globalVar); // works
    }
    console.log(localVar); // ReferenceError
  10. Use functions as values. Functions are objects; you can pass them as arguments to other functions (callbacks) or return them from functions. Example:
    function applyOperation(a, b, operation) {
      return operation(a, b);
    }
    const result = applyOperation(6, 3, (x, y) => x - y); // 3

Common Mistakes

  • Forgetting parentheses when calling. Writing greet instead of greet() passes the function itself, not the result.
  • Missing the return statement. If you expect a value but forget return, the function returns undefined.
  • Shadowing variables. Using the same name for a local variable as a global one can cause confusion; the local one takes precedence inside the function.
  • Misplacing semicolons in function expressions. A function expression assigned to a variable should end with a semicolon after the closing brace.
  • Using arrow functions when you need dynamic this. Arrow functions do not have their own this; if you need it to be bound to the object calling the method, use a regular function.

Tips

  • Use descriptive names. Name functions with verbs (like calculateTotal, getUser) to indicate what they do.
  • Keep functions small. A function should do one thing. If it gets too long, break it into smaller functions.
  • Use const for function expressions. This prevents accidental reassignment.
  • Leverage arrow functions for short callbacks. They are concise and often more readable.
  • Test each function as you write it. Use the browser console (F12) to call it and verify the output.

Troubleshooting

  • Function is not defined. Check for typos in the function name. If using a function expression, make sure it is defined before you call it (they are not hoisted like declarations).
  • Unexpected output or undefined. Verify that you have a return statement if you expect a value. Also check the order of arguments: are you passing them in the correct order?
  • Syntax errors. Look for missing commas, parentheses, or curly braces. In the browser console, the error message usually points to the line number.
  • Scope issues. If a variable is not accessible inside a function, it might be declared with let or const inside another block. Move it to a broader scope if needed.
  • Arrow function returns an object. If you use () => { key: value }, the curly braces are interpreted as a block, not an object. Wrap the object in parentheses: () => ({ key: value }).

Frequently Asked Questions

  • What is the difference between a function declaration and a function expression? Function declarations are hoisted (can be called before they appear in the code), while function expressions are not. Function expressions are assigned to variables and must be defined before they are called.
  • Can I use a function before it is defined? Yes, if it is a function declaration. For function expressions and arrow functions, no—they must be defined first.
  • What does this mean inside a function? The value of this depends on how the function is called. In a regular function, this refers to the object that calls it (or the global object in non-strict mode). Arrow functions do not have their own this; they inherit it from the surrounding scope.
  • How do I return multiple values from a function? You can return an array or an object. For example: return [a, b] or return {sum: a+b, product: a*b}.
  • What is a callback function? A callback is a function passed as an argument to another function, to be executed later. For example, the function passed to Array.prototype.map is a callback.
  • Can I have optional parameters? Yes. You can use default parameters (as shown) or check if an argument is undefined inside the function and handle it accordingly.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.