Functions

A FUNCTION is a NAME for a piece of code

function greetByName(someName) {
  return 'Hello there! It is nice to meet you ' + someName + '.';
}

This is similar to how a variable is a name for a piece of data

Why Name a Piece of Code?

Here are some reasons why this is useful:

Function example

Here's an example function:

function add(firstNum, secondNum) {
  let sum = firstNum + secondNum;
  return sum;
}

Calling a Function

You call a function by referencing the name followed by parentheses:

function add(firstNum, secondNum) {
  let sum = firstNum + secondNum;
  return sum;
}

add(2, 3)   // returns 5
add(12, 30) // returns 42

This is also known as executing the function.

Lab: One Nation, Divisible

A number is divisible by another if when you divide them, the remainder is 0.

Write a function called divisible that:

function divisible(firstNum, secondNum) {
  // write your code here
}

divisible(100, 10)  // true
divisible(100, 7)   // false
divisible(3333, 11) // true
divisible(99, 12)   // false

If you write the solution in a file, use console.log(divisible(100, 7)) to print the return value.

Divisible solution

Hint 1
The modulus operator `%` returns either an integer or zero. Integers are truthy, while 0 is falsy.
Hint 2
You may need to use some logic. You can create a simple control flow with an `if ...else` statement
  
  if(/*this expression evaluates true*/) {
    //do this
  } else {
    //otherwise do this
  }
  
Solution
  
  function divisible(operator, operand) {
    if(operator % operand) {
      return true
    } else {
      return false
    }
  }

  divisible(100, 10) // => true
  

Shouter

Here is a function that takes a String as input, and it returns a shouted version of that String.

function shouter(someString) {
  let loudString = someString.toUpperCase();
  return loudString + '!!!';
}

shouter('i like pizza');
// 'I LIKE PIZZA!!!'

The variable loudString is called a local variable and can only be used inside the function.

Lab: Capitalize

Write a function called capitalize that:

function capitalize(someWord) {
  // your code here
}

capitalize('tomato')
// 'Tomato'

Remember there are many string operations

Capitalize Lab Solution

Hint One
Try getting the first letter from the String using indexing
let firstLetter = string[0]
Hint Two
Try using the method Slice
let restOfString = string.slice(1)
Answer

    function capitalize(word) {
      let firstLetter = word[0];
      let restOfWord = word.slice(1);
      return firstLetter.toUpperCase() + restOfWord.toLowerCase();
    }

    console.log(capitalize('smith'));
    console.log(capitalize('MACGUYVER'));
  
The variables `firstLetter` and `restOfWord` are called *local variables* and can only be used *inside* the `capitalize` function.

Passing Variables as Parameters

When you pass a variable to a function, that variable value is assigned to a parameter.

let nameToShout = 'Grace Hopper';

shouter(nameToShout);
// 'GRACE HOPPER!!!'

The variable name and parameter name DO NOT need to match

Shouter Function Explanation

let nameToShout = 'Grace Hopper';

function shouter(someString) {
  let loudString = someString.toUpperCase();
  return loudString + '!!!';
}

let result = shouter(nameToShout);
Outside Inside Value
nameToShout someString 'Grace Hopper'
loudString 'GRACE HOPPER'
result 'GRACE HOPPER!!!'

Lab: Age Calculator

Write a function named ageInSeconds that:

let age = 27;

function ageInSeconds(num) {
  // your code here
}

ageInSeconds(age);
// 'You are 852055200 seconds old'

Age Function Reverse

Now write a reverse function that:

let ageInSeconds = 852055200;

function ageInYears(seconds) {
  // your code here
}

ageInYears(ageInSeconds);
// 'You are 27 years old'

Solution

Here's one solution for the ageInSeconds calculator:

Answer

  let age = 27

  function ageInSeconds(num) {
    let secondsInMin = 60
    let minInHour = 60
    let hrInDay = 24
    let dayInYr = 365.25

    let secInYr = secondsInMin * minInHour * hrInDay * dayInYr

    let ageInSec = num * secInYr

    return ageInSec
  }

  console.log(ageInSeconds(age))
  

Lab: Supply Calculator

Write a function named supplyCalc that:

supplyCalc(20, 3, 'cookie') 
// 'You will need 87600 cookies to last the rest of your life'
supplyCalc(99, 3, 'cakes')
// 'You will need 1095 cakes to last the rest of your life'
supplyCalc(0, 3, 'pies')
// 'You will need 109500 pies to last the rest of your life'

Inspired by the Lifetime Supply Calculator lab designed for the Girl Develope It! curriculum. The original can be found here

Supply Calculator Solution

Hint 1 Calculate the number of cookies needed per year

let amountPerYear = amountPerDay * 365
Hint 2 Calculate the number of years of life left

let numberOfYears = 100 - age
Solution Use the number of cookies per year, and number of years of life, to calculate the total cookies

function supplyCalc(age, amountPerDay, item) {
  let amountPerYear = amountPerDay *365;
  let numberOfYears = 100 - age;
  let totalNeeded = amountPerYear* numberOfYears;

  return 'You will need' + totalNeeded + ' ' + item + 's to last the rest of your life';
}

Lab: Titleize

Write a function named titleize that:

titleize('all dogs are good dogs');
// 'All Dogs Are Good Dogs'
titleize('eveRY green bus drives fAst');
// 'Every Green Bus Drives Fast'
titleize('FRIDAY IS THE LONGEST DAY');
// 'Friday Is The Longest Day'

Titleize solution

Hint 1 Make a function to capitalize each word

function capitalize(word) {
  let firstLetter = word[0].toUpperCase();
  let restOfWord = word.slice(1).toLowerCase();
  return firstLetter + restOfWord;
}
Hint 2 Split the words in the string into an Array of items

let wordArray = string.split(' ');
Solution Loop over every item in the Array of words, capitalize each, and then add them to a new string

function capitalize(word) {
  let firstLetter = word[0].toUpperCase();
  let restOfWord = word.slice(1).toLowerCase();
  return firstLetter + restOfWord;
}

function titleize(string) {
  let wordArray = string.split(' ');

  let newString = '';
  let wordsModified = 0;

  while (wordsModified < wordArray.length) {
    let currentWord = wordArray[wordsModified];
    let newWord = capitalize(currentWord);
    newString = newString + ' ' + newWord;
    wordsModified = wordsModified + 1;
  }

  return newString.trim();
}

More About Functions

 Previous Next 

Outline

[menu]

/