AlgoInsight

Free lesson · JavaScript Basic to Advance

What Is a Function?

Easy5 min read

What Is a Function?

A function is a reusable block of code that takes inputs, does something with them, and produces an output. That's the surface-level definition, and it's true. But in JavaScript, functions are something more: they're values. You can store them in variables, pass them around, return them from other functions, and use them as building blocks for almost everything the language does.

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

const result = add(5, 3);
console.log(result);

That's the simplest possible function — two inputs, one output. But the line you should focus on isn't the function definition. It's const result = add(5, 3). The function add exists. We're calling it with two arguments. The result of the call gets stored.

This Topic establishes the mental model for functions in JavaScript. Get this right and Modules 5-9 all become easier. Get it wrong and closures, callbacks, and async code will keep surprising you.

Why Functions Exist

Without functions, code would be a flat sequence of instructions. Every action would have to be written out from scratch every time you needed it. Want to validate an email three times? Write the validation logic three times. Want to format a date in five places? Write the formatting logic five times.

Functions solve this by letting you name a piece of logic and reuse it:

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

console.log(greet("Olena"));
console.log(greet("Nikhil"));
console.log(greet("Emeka"));

One definition. Three uses. If you ever need to change how greetings work — add a comma, change the language, capitalize the name — you change one place. This is the single most important reason programming exists. Functions are how you write code once and use it many times.

But functions in JavaScript go further than that. They're not just named blocks of reusable code. They're values. We'll come back to this in Topic 5.7. For now, just internalize: in JavaScript, functions are first-class citizens of the language.

Interactive animation: A value like any other - functions stored in an object, looked up by key, then called.

Anatomy of a Function

Let's break down what a function declaration looks like:

function calculateTotal(price, taxRate) {
  const tax = price * taxRate;
  const total = price + tax;
  return total;
}

console.log(calculateTotal(100, 0.08));

The pieces:

When you call calculateTotal(100, 0.08), JavaScript runs the body with price = 100 and taxRate = 0.08. When it hits the return, it stops and sends back the value. The expression calculateTotal(100, 0.08) evaluates to 108, which then gets logged.

Parameters vs Arguments

These two words sound similar and are often used interchangeably, but they mean specific things:

function multiply(a, b) {   // a and b are PARAMETERS
  return a * b;
}

console.log(multiply(4, 7));   // 4 and 7 are ARGUMENTS

a and b are parameters. They're placeholders that get filled in when the function is called. 4 and 7 are arguments — they're the actual values passed in this particular call.

The distinction matters when you read documentation or interview questions. "How many parameters does this function take?" is asking about the definition. "What arguments are you passing?" is asking about the call.

Interactive animation: Objects passed as arguments - mutation through the parameter reaches back to the caller, reassignment does not.

Functions Without Parameters or Return Values

A function doesn't have to have parameters. And it doesn't have to return anything.

function sayHello() {
  console.log("Hello!");
}

sayHello();   // no arguments to pass

This function has no parameters (empty ()) and no return statement. It runs its body and exits. Calling it produces a side effect — printing to the console — but doesn't produce a return value.

If you assign the result of a function with no return to a variable, you get undefined:

function noReturn() {
  console.log("I print but don't return");
}

const value = noReturn();
console.log(value);   // undefined

Every function in JavaScript returns something. If you don't explicitly return a value, JavaScript silently returns undefined for you.

Interactive animation: The ASI trap on return - the value never makes it out, so the call returns undefined.

Calling a Function

Functions don't run automatically. They only run when you call them — also called invoking them. Calling a function means writing its name followed by parentheses:

function announceArrival() {
  console.log("She's here!");
}

// At this point, the function is defined but hasn't run.
// Nothing has been logged yet.

announceArrival();   // NOW it runs
announceArrival();   // and again

This distinction matters because functions in JavaScript are values. If you write announceArrival without the parentheses, you're referring to the function itself, not calling it:

function announceArrival() {
  console.log("She's here!");
}

console.log(announceArrival);     // logs the function value
console.log(announceArrival());   // calls it and logs undefined (since it returns nothing)

The first console.log shows the function itself — something like [Function: announceArrival]. The second console.log shows the result of calling it, which is undefined. The function does print "She's here!" as a side effect of being called.

graph LR
    A[announceArrival] --> B[the function value itself]
    C["announceArrival()"] --> D[the result of calling it]

    style A fill:#3b82f6,color:#fff
    style C fill:#7c3aed,color:#fff
This diagram shows the critical distinction between referring to a function and calling it. The name announceArrival, without parentheses, is the function value itself — you can store it, pass it around, or assign it to another variable. The expression announceArrival with parentheses is a function call — it runs the function and produces a result. Confusing these two is a very common JavaScript bug, especially with callbacks and event handlers.

This distinction is the foundation for everything in Modules 5 and 6. Functions are values. Calling a function is an action. The two are not the same thing.

Interactive animation: Referencing vs calling - without the parentheses you get the function itself, with them you run it.

A Brief Mental Model

When you read a line of JavaScript that involves a function, ask yourself:

  1. Is this defining a function or calling one? If you see function name(...) or const name = function(...), you're defining. If you see name(...), you're calling.
  2. What's going into the function? Look at the arguments.
  3. What's coming out? Look at where the return value gets used. If the result isn't stored or used, the function is probably being called for its side effects (like console.log).
  4. What side effects might it have? Some functions just produce return values. Others modify external state — change variables, write to files, update the DOM. Be aware of which kind you're calling.

Once these four questions become automatic, reading JavaScript code becomes much faster.

Common Pitfalls

Warning: The function basics traps.

Forgetting the parentheses when calling. myFunction refers to the function. myFunction() calls it. If you write setTimeout(myFunction, 1000) you're passing the function so it can be called later. If you write setTimeout(myFunction(), 1000) you're calling it immediately and passing whatever it returned.

Forgetting to return. A function without a return statement returns undefined. If you wrote a function expecting it to "produce" a value, but forgot the return, you'll get undefined back and not know why. Always trace through whether your function actually returns what you think it does.

Confusing parameters and arguments in conversation. Not a bug exactly, but using these terms incorrectly signals beginner status in interviews. Parameters are in the definition. Arguments are in the call.

Why This Matters in Interviews

Interview: Interviewers don't ask "what is a function?" directly. They watch how you use functions throughout the interview. The signals they're listening for: do you decompose problems into well-named functions, or do you write everything as one giant block? Do you reach for callbacks naturally, or do you avoid them? Do you understand that functions are values?

Topic 5.8 — Interview Lens: Functions and Higher-Order Patterns — covers the deeper interview-prep treatment of functions, including the specific puzzles that test whether you understand functions-as-values.

Try It

Exercise: Write a function called describePerson that takes a name and an age and returns a sentence describing them. Use it three times with different inputs.

Then write a function called greet that takes no parameters and returns the string "Hello!". Call it and store the result.

Finally, write a function called printGreeting that takes no parameters, doesn't return anything, but prints "Hello!" to the console.

Run all three. Notice the difference: describePerson and greet produce values you can use. printGreeting causes output as a side effect. The distinction between return values and side effects is one of the most important things to internalize about functions.

Back to JavaScript Basic to Advance