Skip to content

Writing functions to make programs modular

Functions

A function is a set of instructions that take an input and get an output, to perform a certain task.

Functions are the ACTION part of programming.

To define a function in JavaScript you use the function keyword.

A function declaration uses the function keyword, followed by:

  • The name of the function.
  • The parameters of the function, enclosed in brackets (parameter1, parameter2) after the name, separated by commas.
  • If a function has no parameters the name is followed by an empty pair of brackets ().
  • The statements that form the actions of the function, are enclosed in curly brackets {}.

Example:

js
function pets(cats, dogs){
    return cats + dogs;
}
function pets(cats, dogs){
    return cats + dogs;
}

The keyword return is used to specify the value returned by the function.

Defining a function does not run (or execute) it. To execute a function you need to call it by typing its name and then any values you want to use as parameters in brackets beside this. If there are no parameters, simply call the function by typing its name in front of a set of empty brackets ().

Example:

js
pets(numCats, numDogs);
pets(numCats, numDogs);

Sometimes if you have a lot of code that will be used many times in a program, instead of writing out all the instructions again and again, you can put them in a function and just use a one line function call to do the same thing. This makes your code modular and more efficient.

The special term return is used to stop the function running, then specify the value returned and give it to the function caller (put it into memory). After this other following statements in the function will run.

Functions can be used as values, and in expressions.

Example:

js
let numFish = function(goldfish, carp) {
    return goldfish + carp;
}

console.log(numFish(5,2));
let numFish = function(goldfish, carp) {
    return goldfish + carp;
}

console.log(numFish(5,2));

Example:

js
let numPets = pets(numCats, numDogs);
console.log(numPets);
let numPets = pets(numCats, numDogs);
console.log(numPets);

Function scope

Function scope: Variables declared within a function, cannot be accessed outside of it. Local variables have function scope and can only be accessed from within a function.

The difference between global and local variables:

  • Global variables are declared OUTSIDE functions (typically at the beginning of the program). They are retained throughout the entire program lifetime.
  • Local variables are declared INSIDE functions. They are thrown away when the function returns.

Example:

js
let numPlants = 0;

function plants(){
    let spiderPlant = 3;
    let cactus = 5;
    let rubberPlant = 2;
    numPlants = spiderPlant + cactus + rubberPlant;
    console.log("I originally had " + numPlants + " plants.");
    return numPlants;
}

let boughtPlants = Math.floor(Math.random() * 10);
console.log("I bought " + boughtPlants + " plants.");

function plantsUpdate(newPlants){
    let originalPlants = plants();
    numPlants = originalPlants + newPlants;
    console.log("I now have " + numPlants + " plants.");
    if(numPlants < 15){
        console.log("That's quite a few plants!");
    } else {
        console.log("That's a lot of plants!");
    }
}

plantsUpdate(boughtPlants);
let numPlants = 0;

function plants(){
    let spiderPlant = 3;
    let cactus = 5;
    let rubberPlant = 2;
    numPlants = spiderPlant + cactus + rubberPlant;
    console.log("I originally had " + numPlants + " plants.");
    return numPlants;
}

let boughtPlants = Math.floor(Math.random() * 10);
console.log("I bought " + boughtPlants + " plants.");

function plantsUpdate(newPlants){
    let originalPlants = plants();
    numPlants = originalPlants + newPlants;
    console.log("I now have " + numPlants + " plants.");
    if(numPlants < 15){
        console.log("That's quite a few plants!");
    } else {
        console.log("That's a lot of plants!");
    }
}

plantsUpdate(boughtPlants);

Example:

js
let numGoldfish = Math.floor(Math.random() * 10);
let numCarp = Math.floor(Math.random() * 10);
let numFish = 0;
let sleepy = true;

function fishTale(){
    let randomNumber = Math.floor(Math.random() * 2);
    if(randomNumber == 0){
        sleepy = false;
    } else {
        sleepy = true;
    }
    if(sleepy == true){
        let sleepState = "My goldfish are sleepy today.";
        console.log(sleepState);
        return sleepState;
    } else {
        let sleepState = "My goldfish are awake today.";
        console.log(sleepState);
        return sleepState;
    }
}

function fishTank(goldfish, carp, totalFish){
    console.log("I have " + goldfish + " goldfish.");
    console.log("I have " + carp + " carp.");
    totalFish = goldfish + carp;
    console.log("In total I have " + totalFish + " fish.");
}

fishTank(numGoldfish, numCarp, numFish);
let goldfishHealth = fishTale();
let numGoldfish = Math.floor(Math.random() * 10);
let numCarp = Math.floor(Math.random() * 10);
let numFish = 0;
let sleepy = true;

function fishTale(){
    let randomNumber = Math.floor(Math.random() * 2);
    if(randomNumber == 0){
        sleepy = false;
    } else {
        sleepy = true;
    }
    if(sleepy == true){
        let sleepState = "My goldfish are sleepy today.";
        console.log(sleepState);
        return sleepState;
    } else {
        let sleepState = "My goldfish are awake today.";
        console.log(sleepState);
        return sleepState;
    }
}

function fishTank(goldfish, carp, totalFish){
    console.log("I have " + goldfish + " goldfish.");
    console.log("I have " + carp + " carp.");
    totalFish = goldfish + carp;
    console.log("In total I have " + totalFish + " fish.");
}

fishTank(numGoldfish, numCarp, numFish);
let goldfishHealth = fishTale();

References

https://eloquentjavascript.net/02_program_structure.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Content CC BY 4.0 | Code AGPL 3.0