Year of the Pig explainer


#1

The aim of this puzzle: Use the return keyword to return a value from a function.

Walkthrough of the solution: The return keyword tells a function to return a value to the caller.

Not all functions require return statements. For example, console.log() will output text to the console, but is not used to return a value.

In this puzzle, the lengthOfName function takes a parameter called name, and then calculates name.length. However, it is missing the return keyword, so this value is not able to leave the function, and is lost as soon as it is calculated.

This means that when the function is called inside the console.log() statement, it will return undefined.

To complete the puzzle, use the return keyword to return name.length. Now when the function is called, this value will be passed to the console.log().

Sample code solution:
(Tap below to reveal)

let pigName = 'Wilbur';
let pigAge = 1;

function lengthOfName(name) {
  return name.length;
}
function ageInHumanYears(age) {
  return 14 + 4 * age;
}
console.log('The length of the name ' + pigName + ' is ' + lengthOfName(pigName) + ' characters.');
console.log(pigName + ' is ' + ageInHumanYears(pigAge) + ' in human years.');

JavaScript Concepts: Return Statements, Console, Strings, Function Declarations, Calling Functions, Variable Declarations (let)