I'm so lost with functions :(

https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-functions/projects/rock-paper-scissors-javascript

This is my code:

const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === ‘rock’ || userInput===‘paper’ || userInput ===‘scissors’ || userInput ===‘bomb’) {
return userInput;
} else {
console.log(‘not a valid choice’);
}
};

function getComputerChoice() {
const x = Math.floor(Math.random()*3);
switch(x) {
case 0:
return ‘rock’;
break;
case 1:
return ‘scissors’;
break;
case 2:
return ‘paper’;
break;
};
}

const determineWinner = (userChoice,computerChoice) => {
if (userChoice === computerChoice) {
return ‘It’s a tie!’;
}
if (userChoice === ‘rock’) {
if (computerChoice === ‘paper’) {
return ‘Computer wins!’;
} else {
return ‘You win!’;
}
}
if (userChoice === ‘paper’){
if (computerChoice === ‘scissors’) {
return ‘Computer wins!’;
}else {
return ‘You win!’;
}
}
if (userChoice === ‘scissors’) {
if (computerChoice === ‘rock’) {
return ‘Computer wins!’;
} else {
return ‘You win!’;
}
}
if (userChoice === ‘bomb’) {
return ‘You win!’;
}
};

const playGame = () => {
const userChoice = getUserChoice(‘scissors’);
const computerChoice = getComputerChoice()
console.log(You threw ${userChoice});
console.log(Computer threw ${computerChoice});
console.log(determineWinner(userChoice,computerChoice));
};

console.log(playGame());

I have a few problems:

  1. I don’t understand why we needed userChoice and computerChoice parameters, why couldn’t we have simply kept getUserChoice and getComputerChoice.

  2. How are empty parameters allowed?
    E.g. const playGame = () => {}
    This has nothing inside the parameter so what does this mean?

I spent over 2 hours on this and my head hurts. Please could someone explain?

Do you mean inside the playGame function? If so, consider what happens if you were to re-write the function like so:

const playGame = () => {
  console.log(You threw ${getUserChoice('scissors')}); //you call the getUserChoice function
  console.log(Computer threw ${getComputerChoice()}); //call the getComputerChoice function
  console.log(determineWinner(getUserChoice('scissors'), getComputerChoice())); //call both functions again
};

In addition to calling each function twice which is inefficient, what are the odds that getComputerChoice() will return the same value both times? What happens if it doesn’t? You could have output like this:

You threw scissors
Computer threw paper //first call to getComputerChoice returns paper
Computer wins! //second call to getComputerChoice returns rock (not printed)
undefined //consider why this is printed when your code is executed

This could lead to thinking that there’s a problem within the determineWinner function even though it’s working properly.

There is no requirement for a function to accept or use parameters. Using the arrow function syntax, when there are no parameters, or if there is more than one parameter, we must use the parenthesis as you’ve done in your code.

1 Like

I see that is a Eureka moment thank you so much! So by using const computerChoice = getComputerChoice(), you now have a constant value for getComputerChoice(), since computerChoice isn’t a function?

I really am thankful for your help! That explains why I thought determineWinner wasn’t working.
I have a few follow up questions:

  1. I do keep getting undefined even with my “correct code” but I couldn’t figure out why? What is the reason for this?
  2. To confirm, you should then only put variables inside parameters if they are actively being used for some sort of calculation? So getComputerChoice() is empty because the constant x is not entered in the calculation. However, determineWinner() has to feature the userChoice and computerChoice variables because it is used in the calculation? Are userChoice and computerChoice variables then?
  3. Can functions be used inside parameters and if so is this what a helper function is?

Thanks!
2.

In JavaScript, when a function has no explicit return statement, it implicitly returns undefined, so if we take into consideration where in the ouput undefined appears, it seems likely that it was the last thing printed. console.log() is a built in method that prints whatever we include as an argument to the console. For undefined to show up in the console it had to come from a call to console.log(). The last call in your code to console.log() is here:

console.log(playGame());

This may partially answer your third question. In the line above, a function call is being passed as the argument to the console.log() method (Note: a method is a function that belongs to an object or class). Since playGame doesn’t explicitly return a value (it calls other functions including console.log(), but doesn’t have an explicit return statement), it returns undefined. That return value is what gets printed by the console.log method. To avoid undefined being printed you have options. Most simply, you can call the playGame function without logging it’s return value:

playGame();

Otherwise, you could have playGame return something like a message at the end that indicates it has completed its tasks successfully, or you could construct a string to be returned instead of having the function log the output to the console:

const playGame = () => {
  const userChoice = getUserChoice('scissors');
  const computerChoice = getComputerChoice()
  return `You threw ${userChoice}\nComputer threw ${computerChoice}\n${determineWinner(userChoice, computerChoice)}`
  
};

console.log(playGame());

For your second question, let’s clarify the terminology. When we declare a function, it may or may not accept parameters depending on our needs. When we use those parameters inside the function they behave as local variables. When we call a function, the values passed are arguments. The values assigned to the arguments are assigned to the parameters of the function. If the function doesn’t require values from outside to complete its task(s), then there is no reason to use parameters. (Hopefully that made sense.)

Yes, functions can be passed as arguments, and assigned to the parameters of other functions. ‘Helper Function’ is kind of a general term for a function that ‘helps’ another function by completing part of the overall task.

Here’s a trivial example of functions interacting with each other:

const apply = (someFunction, someValue) => {
  return someFunction(someValue);
};

const addCheese = sandwich => sandwich += " and cheese";

const addJelly = sandwich => sandwich += " and jelly";

const addKetchup = sandwich => sandwich += " with ketchup";

const improveSandwich = blandSandwich => {
  let whichFunction = addKetchup; //default value
  if(blandSandwich == "ham") {
    whichFunction = addCheese;
  };
  if(blandSandwich == "peanut butter") {
    whichFunction = addJelly;
  };
  return `Your ${blandSandwich} sandwich is now a ${apply(whichFunction, blandSandwich)} sandwich. Enjoy!`;
};

console.log(improveSandwich("ham"));
console.log(improveSandwich("peanut butter"));
console.log(improveSandwich("bologna"));
console.log(improveSandwich("banana and marshmallow"));

Output:

Your ham sandwich is now a ham and cheese sandwich. Enjoy!
Your peanut butter sandwich is now a peanut butter and jelly sandwich. Enjoy!
Your bologna sandwich is now a bologna with ketchup sandwich. Enjoy!
Your banana and marshmallow sandwich is now a banana and marshmallow with ketchup sandwich. Enjoy!

1 Like

That makes soo much sense thank you for taking the time to explain it all!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.