1

How do I log the variable totalCost to the console? I am getting an error when trying to run this code

Tried using console.log(totalCost);

function monitorCount(rows, columns) {
  return rows * columns;
}

function costOfMonitors(rows, columns){
  return monitorCount(rows, columns) * 200;

  const totalCost = costOfMonitors(5, 4);

}

console.log(totalCost);
5
  • Are you ever calling the function? And you need to return from the function. Also, always post the error you're getting. Commented Apr 9, 2019 at 14:28
  • Why is the const totalCost inside the costOfMonitors function? Commented Apr 9, 2019 at 14:28
  • You return from your costOfMonitors function before you set totalCost Commented Apr 9, 2019 at 14:28
  • @Carcigenicate - despite that, totalCost is scoped, so the OP is going to get an totalCost is not defined error anyway Commented Apr 9, 2019 at 14:28
  • What does the error tell you? What do you expect to be logged to the console from exactly this code and why? (Honestly, there is a variety of problems in this code...) Commented Apr 9, 2019 at 14:29

1 Answer 1

3

The return keyword ends a function after the code in its line has been executed.

Also, totalCost is in the scope of your countOfMonitors function, so you can't access it from somewhere else.

To add to that, even if you swapped your return statement and your declaration, you would create an infinite loop with recursion, as you're calling a the same function inside a function.

This should get it working:

function monitorCount(rows, columns) {
  return rows * columns;
}

function costOfMonitors(rows, columns){
  return monitorCount(rows, columns) * 200;
}
const totalCost = costOfMonitors(5, 4);
console.log(totalCost);
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant thanks for that! worked a treat!!!! new to this Java Script!!!!! ahhhhhh!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.