Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 156 ยท Functions

Functions

Learn to write and call JavaScript functions. Covers function declarations, function expressions, hoisting, naming and how to split code into small pieces.

A function is a named, reusable piece of code. You write the steps once, give them a name, and then run them whenever you need them by calling the function. You've been calling functions since your first lesson: console.log(), Math.round() and Number() are all functions that someone else wrote.

Functions are the most important building block in JavaScript. They let you avoid repeating yourself, give meaningful names to chunks of logic, and break a big problem into small pieces you can understand and test one at a time. This lesson covers the two main ways to create a function, how calling works, and how to name and size your functions well. The next lessons dig into parameters and return values.

Declaring and calling a function

The most common way to create a function is a function declaration:

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

It has four parts:

  1. The function keyword.
  2. A name, here greet.
  3. Parentheses for parameters, the inputs. This one has none.
  4. A body in curly braces: the code that runs when the function is called.

Declaring a function doesn't run it. It just stores the instructions under a name. To run them, call the function by writing its name followed by parentheses:

JS Declare once, call many times

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When JavaScript reaches greet(), it jumps into the function body, runs it from top to bottom, then returns to where it was called and carries on. The parentheses matter: greet on its own refers to the function without running it, while greet() calls it.

Inputs and outputs, briefly

A function becomes much more useful when it takes inputs and gives back an output. Inputs are listed as parameters in the parentheses; the values you pass in a call are called arguments. The return keyword sends a value back to the caller:

JS Parameters and return

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A call to square(7) is an expression: it produces a value (49) that you can store, log or use in a bigger calculation. Both topics get their own lessons, so for now just notice the pattern: data goes in through the parentheses and comes out through return.

Why write functions?

Look at this code that formats prices in three places:

JavaScript
console.log("Shirt: $" + (19.5).toFixed(2));
console.log("Shoes: $" + (64).toFixed(2));
console.log("Hat: $" + (12.25).toFixed(2));

If the format changes, say to add a currency code, you'd have to edit every line, and you'd probably miss one in a real program. Put the logic in a function and there is exactly one place to change:

JS Removing repetition

Press Run (or Ctrl + Enter) to see the console output here.

No output.

That's the first benefit: reuse without repetition. The others matter just as much:

  • Naming. formatPrice(...) tells the reader what happens without making them read how.
  • Decomposition. A big task becomes a few small functions, each easy to understand on its own.
  • Testing. A small function with clear inputs and outputs is easy to try out and check.

Function expressions

A function is a value in JavaScript, just like a number or a string. That means you can create one inside an expression and store it in a variable. This is a function expression:

JavaScript
const greet = function () {
  console.log("Hello!");
};

greet(); // called exactly the same way

Notice the semicolon at the end: the whole thing is a const declaration, and the function is just the value being assigned. The function itself has no name here, so it's called anonymous, although JavaScript still records greet as its name property.

Because functions are values, you can pass them around like any other data:

JS Functions are values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Treating functions as values is one of JavaScript's superpowers. It's the basis of callbacks, event handlers and array methods like map. Higher-Order Functions and Callbacks explores it in depth, and Arrow Functions introduces a shorter syntax for function expressions.

Named function expressions

A function expression can also have its own name: const factorial = function fact(n) { โ€ฆ }. That inner name, fact, is visible only inside the function body. It shows up in error stack traces and lets the function call itself even if the outer variable is reassigned. You won't need it often, but you'll recognize it now.

Declarations vs expressions: hoisting

There's one practical difference between the two forms. Function declarations are hoisted: JavaScript sets them up before running any code in their scope, so you can call one above the line where it's written. Function expressions stored in const or let are not available until the assignment line runs.

JS Hoisting in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hoisting lets you put the main logic at the top of a file and the helper functions below it, which many people find easier to read. The full story, including the "temporal dead zone" behind that error, is in Scope and Hoisting.

Which form should you use? Both are fine and widely used. Many developers use declarations for named, top-level functions and expressions (usually arrow functions) for short functions passed to other functions. Pick a style and be consistent.

Function forms at a glance

You now know several ways to write a function. Here they are side by side:

Form Example Hoisted? Has its own name?
Declaration function add(a, b) { โ€ฆ } yes add
Anonymous expression const add = function (a, b) { โ€ฆ } no inferred: add
Named expression const add = function sum(a, b) { โ€ฆ } no sum (visible only inside)
Arrow function const add = (a, b) => a + b no inferred: add
IIFE (function () { โ€ฆ })() not stored none

IIFEs

An IIFE (immediately invoked function expression) defines a function and calls it in the same breath. The parentheses around the function turn a declaration into an expression, and the trailing () runs it. It is useful when you need a private scope or a multi-step calculation for a single value. See Functional Programming for more.

Functions are objects with properties

Every function is an object, so it has properties. Two are built in: name (the function's name, inferred from the variable when you assign an anonymous function) and length (how many parameters come before the first default or rest parameter). You can also attach your own properties, for example a call counter.

JS name, length, IIFEs and custom properties

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Optional parameters and "overloading"

Some languages let you define several functions with the same name and different parameter lists (overloading). JavaScript does not: if you declare two functions with the same name, the second silently replaces the first. Instead, you write one function that inspects what it received. Three techniques cover almost every case:

  1. Optional parameters with defaults (the simplest).
  2. Checking arguments.length or a rest array, and the typeof of each value.
  3. An options object for many optional settings.
JS One function, several call shapes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Keep overload-style functions small. If one function handles more than three shapes of input, split it into clearly named functions (circleArea, rectArea); callers will thank you. Parameters covers defaults, rest parameters and options objects in depth.

Naming functions

Good function names make code read like a description of what it does. A few conventions:

  • Start with a verb. Functions do things: calculateTotal, sendInvite, formatDate, parseQuery.
  • Use camelCase, like variables: getUserName, not get_user_name or GetUserName (PascalCase is reserved for classes).
  • Booleans read as questions. Functions that answer yes or no often start with is, has or can: isValidEmail, hasPermission, canEdit.
  • Be specific. handle() or doStuff() tell the reader nothing. If a good name is hard to find, the function may be doing too many things.

One function, one job. If you describe what a function does and the sentence contains "and", like "validates the form and saves it and shows a message", consider splitting it. Short functions with clear names are easier to read, reuse and fix than one long function.

Common mistakes

  • Forgetting the parentheses. greet; does nothing, and console.log(greet) prints the function itself instead of calling it.
  • Calling too early with expressions. A const function can't be used before its line runs.
  • Reusing a built-in name. A function called alert or Number hides the built-in one in that scope. Pick distinct names.
  • Duplicate declarations. Two function save() declarations in the same scope don't cause an error; the later one silently replaces the earlier one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given function hi() { console.log("hi"); }, what does the line hi; do?

    Only hi() calls the function. Without the parentheses, hi is just a reference to the function value.
  2. 2. Which call works because of hoisting?

    Function declarations are hoisted with their body, so they can be called earlier in the scope. Function expressions in const or let are not ready until their line runs.
  3. 3. In function add(a, b) { return a + b; } and the call add(2, 3), what are 2 and 3?

    a and b are parameters, the names in the definition. The values passed in a call, 2 and 3, are arguments.
  4. 4. What does typeof function () {} produce?

    Functions are a special kind of object, but typeof reports them as "function".
  5. 5. Which is the best name for a function that checks whether a cart is empty?

    Yes/no functions read best as questions that start with is, has or can, written in camelCase.

Summary

  • A function is a named, reusable block of code. Declaring it stores it; calling it with () runs it.
  • Parameters are a function's inputs, arguments are the values you pass, and return sends a value back.
  • Functions remove repetition, give names to logic, and break big problems into small, testable pieces.
  • A function expression creates a function as a value, often stored in a const. Functions can be stored, swapped and passed around like any other value.
  • Function declarations are hoisted; expressions in const/let can't be used before their line.
  • Every function is an object with name and length properties; an IIFE runs a function expression immediately.
  • JavaScript has no overloading (a duplicate name replaces the first); use defaults, argument checks or an options object.
  • Name functions with verbs in camelCase, keep each function to one job, and use is/has/can for yes-or-no answers.

Next: Parameters and Arguments โ€” default values, rest parameters and passing objects.