RivoCode

JavaScript Fundamentals · Functions · Lesson 12 of 48

Declaring Functions

Concept

Declaring Functions

Functions bundle reusable logic. Define one with the function keyword, then call it any number of times.

Writing the same logic as a function instead of copy-pasting it everywhere means you only have to fix a bug, or change the behavior, in one place.

By the end of this lesson
  • Explain the core idea behind Declaring Functions.
  • Predict output before running a change.
  • Test one realistic and one unusual input.
  • Use the result to make the next decision.
How to study this page
  1. 1. Read one concept.
  2. 2. Change the example.
  3. 3. Run, compare, and explain.
  4. 4. Complete the challenge below.
Syntax
function functionName(parameter1, parameter2) {
  // code
  return value;
}
ExampleRunnable
function greet(name) {
  return "Hello, " + name + "!";
}
console.log(greet("Ibrohim"));
Try it Yourself »
A function with no parameters
function sayHi() {
  console.log("Hi there!");
}
sayHi();

Good to know

A function that doesn't explicitly return anything returns undefined by default.

Self-check before continuing

Without looking at the example, describe what changes when you modify one input in Declaring Functions. Then reopen the editor and prove your explanation with a small test.

You are ready to continue when you can predict, test, and explain the result.

Your turn

Write a function square(n) that returns n multiplied by itself.

Loading editor…

Console

Output will appear here...