Year of the Dog explainer


#1

Aim of the puzzle: Use the return keyword to return a value from a function.
Walk through of solution: The puzzle begins with two variables declared, dogName (a string) and dogAge (a number). Feel free to change the values of the two variables to a different string and number as you see fit.

The function lengthOfName() is also declared. This function takes a string, uses the .length string method to calculate the length of the string, and then returns that value using the return keyword.

The function ageInHumanYears() has also been declared. It takes an age (a number) and calculates age * 7, but is not yet using the return keyword. Because there is no return, the function will instead return undefined.

Try running the starter code when the puzzle loads. Because ageInHumanYears() does not have the return keyword, the following text will be printed to the console:

'The length of the name Pooky Mulder is 12 characters.'
'Pooky Mulder is undefined in human years.'

ageInHumanYears() is still performing the calculation age * 7, but it isn’t returning the answer, so undefined is being printed instead.

To complete the puzzle, replace age * 7 with return age * 7. Now when the program runs, the correct text will print to the console:

> 'The length of the name Pooky Mulder is 12 characters.'
> 'Pooky Mulder is 14 in human years.'

Because the return keyword has been added, the value of age * 7 can now be accessed outside the function.

Sample code solution:

let dogName = 'Pooky Mulder';
let dogAge = 2;

function lengthOfName(name) {
    return name.length;
}
function ageInHumanYears(age) {
    return age * 7;
}
console.log('The length of the name ' + dogName + ' is ' + lengthOfName(dogName) + ' characters.');
console.log(dogName + ' is ' + ageInHumanYears(dogAge) + ' in human years.');

Javascript Concepts: Return, Function Declarations, Variables with Let, String Methods