No history yet

Function Basics

Packaging Your Code

Imagine you have a task you need to do repeatedly, like making your morning coffee. You follow the same steps every day: grind beans, add water, press start. In programming, we often have tasks that need to be repeated. Instead of writing the same lines of code over and over, we can package them into a reusable block called a function.

A function is a named, reusable block of code designed to perform a specific task.

Using functions is a core principle of good programming. It helps keep your code organized, readable, and easy to fix or update. When you break a large program into smaller, self-contained functions, you're creating modular code. Each module (or function) handles one part of the job, making the whole system easier to manage.

Creating Functions

There are a couple of common ways to create a function in JavaScript. Let's start with the most direct method: a function declaration.

A function declaration starts with the function keyword, followed by the name you want to give your function, a set of parentheses (), and a pair of curly braces {} that contain the code to be executed.

function showGreeting() {
  console.log("Hello, world!");
}

Here, we've created a function named showGreeting. The code inside its curly braces will print the message "Hello, world!" to the console. At this point, we've only defined the function. We've written the recipe, but we haven't actually made anything yet.

Another way to create a function is with a function expression. This method involves creating a function and assigning it to a variable.

const sayGoodbye = function() {
  console.log("See you later!");
};

This code creates a function that logs "See you later!" and assigns it to a constant named sayGoodbye. For now, you can think of declarations and expressions as two different styles for achieving the same goal.

Running a Function

Defining a function doesn't run its code. To execute the code inside a function, you need to call (or invoke) it. You do this by writing the function's name followed by parentheses.

// First, we declare the function
function showGreeting() {
  console.log("Hello, world!");
}

// Now, we call it
showGreeting();

When the line showGreeting(); is run, the program jumps to the showGreeting function and executes the code inside it. You'll see Hello, world! printed in the console.

The real power of functions comes from their reusability. You can call a function as many times as you need.

showGreeting();
showGreeting();
showGreeting();

This would print "Hello, world!" to the console three times, without you having to rewrite the console.log statement each time. You wrote the code once and can now use it whenever you want.

Quiz Questions 1/5

What is the primary purpose of a function in programming?

Quiz Questions 2/5

The practice of breaking a large program into smaller, self-contained functions is known as creating ________ code.