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: It is best practice to write the function code before calling it, so your code is easier to read and understand.
Challenge
EasyWrite 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.
Cheat sheet
A function is a sequence of code that has a name, used to reuse code multiple times.
To declare a function:
function functionName() {
code;
}To call/execute a function:
functionName();Example:
function greet() {
console.log("Welcome to Coddy");
}
greet(); // calls the functionBest practice: It is best practice to write functions before calling them.
Try it yourself
// Write the function below
let n = parseInt(inp); // Don't change this line
// Execute your function n times with a loopThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False