Penny Pincher explainer


Aim of the puzzle: Complete the inCents() function to convert dollars into pennies.
Walk through of solution: The starter code begins by declaring the variable wallet and giving it the value 20. Below that the function inCents() is declared, but not finished. It takes the parameter dollars and assigns this to wallet.

Finish the inCents() function by tapping on dollars inside the body { } of the function to highlight it and bring up the keyboard. Then use the keys * and num to multiply dollars * 100. When this function is finished, run the code to complete the puzzle.

When the program runs, the code will print the first console.log() statement, which prints out the value of wallet. The inCents() function is then called, and given wallet as an argument. The function will multiply this number by 100 and assign it back to wallet. The second console.log() statement will then print out the value of wallet, which is now 2000.
Sample code solution:

let wallet = 20;

function inCents(dollars) {
    wallet = dollars * 100;

console.log('You have ' + wallet + ' dollars.');
console.log('You have ' + wallet + ' cents.');

Javascript Concepts: Arithmetic Operators (*), Binary Expression (+ concatenation), Calling Functions, Function Declarations, Code Block (function), console.log() , Variable Scope (let)


I dont understand why we have defined ‘wallet’ but we didnt need to assign ‘dollars’. How does the computer know that ‘dollars’ refers to the value of ‘wallet’?


The dollars variable is called a Parameter. When a function is declared, like function inCents(...), the parentheses may contain a parameter. The parameter will get assigned a value once the function is called (“calling a function” just means “running a function”).

In this puzzle, the inCents(...) function is called with wallet as the argument. This means the wallet variable, which is storing the value 20, gets plugged into the inCents() function as the new value for the dollars parameter.

Parameters: placeholder variables that are used inside a function declaration
Arguments: values assigned to the parameter when calling the function

function add(x, y) {
  console.log(x + y);

add(10, 20);

In this example, x and y are parameters and the numbers 10 and 20 are arguments. When you call a function, you can imagine a step where each of the arguments gets stores in the parameters. It’s important that you have the arguments in the right order.

         add(10, 20);
              ↓   ↓
function add( x,  y) {
  console.log(x + y);