Menu
Coddy logo textTech

Declare a Function

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 45 of 77.

A function is a sequence of code that has a name. The purpose of a function is to reuse a piece of code multiple times.

For example, take a look at this code:

console.log("Welcome to Coddy");
console.log("New session...");
console.log("Welcome to Coddy");
console.log("Another session...");
console.log("Welcome to Coddy");

We use the same code console.log("Welcome to Coddy") over and over again. Another issue with this code is that if we wanted to change the message: Welcome to Coddy to something different, like "Welcome aboard" it would have to change 3 different lines of code. To solve this issue, we will use functions.

To declare a function, we use the following syntax:

function functionName() {
    code;
}

For our example, we will create a function named greet and it will look like this:

function greet() {
    console.log("Welcome to Coddy");
}

To use/call/execute the function, we write greet():

greet();
console.log("New session...");
greet();
console.log("Another session...");
greet();

This will result in the same output as above.

Note: In JavaScript, function declarations are hoisted, meaning they can technically be called before they appear in the code. However, it is best practice to write functions before calling them to keep your code clear and readable.

challenge icon

Challenge

Easy

Write a program that gets one input, a number (given). The input number indicates how many times to execute the below function. 

Create a function that calculates the sum of all of the numbers between 1 and 10000 (including) and prints it, name the function however you like.

Note! In your code, write the function before it's call/execution statements.

Try it yourself

// Write the function below


let n = parseInt(inp); // Don't change this line

// Execute your function n times with a loop
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals