Declaring and Calling a Function

Grade 6, page 2 of 11. A one-minute read.

Here's how you make a function:

JavaScript
function showBanner() {
  console.log("=====================");
  console.log("  Welcome, friend!  ");
  console.log("=====================");
}

Let's break it down:

  • function is the keyword that says "I'm making a function."
  • showBanner is the function's name. Same naming rules as variables (camelCase, no spaces).
  • () the parentheses hold the function's inputs. This one has none, so they're empty.
  • { } the curly braces contain the body: the code that runs when the function is used.

This is called declaring (or defining) a function. But here's the thing: if you run that code... nothing happens. Nothing is printed at all!

That's because declaring a function is like writing a recipe on a card. Writing the recipe doesn't cook anything. To actually make the dish, you have to follow the recipe. In programming, we call that calling the function (or "invoking" it, if you're feeling fancy). You call a function by writing its name followed by parentheses:

JavaScript
showBanner();

It prints

=====================
  Welcome, friend!  
=====================

And you can call it as many times as you like:

JavaScript
showBanner();
console.log("Some other stuff happens here...");
showBanner();

It prints

=====================
  Welcome, friend!  
=====================
Some other stuff happens here...
=====================
  Welcome, friend!  
=====================

Now if someone wants stars instead of equals signs, you change it in one place, and every banner updates.

Watch outDon't forget the parentheses

showBanner() calls the function. showBanner without parentheses just refers to the function without running it, like pointing at the vending machine without pressing any buttons. If your function "isn't doing anything," check that you included the () when you called it.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning