Created a 2 value calculator and then read this

It seems that for something small like this, it does work. Are there issues that arise from using console.log to return a value?

When testing calculations or viewing the state of some data in your code, console.log() works well. This text is talking specifically about return values.

If the goal of a function is to show output in the console, the console.log() might be what you want. But if a function’s output is meant to be fed into another function, then you have to use return rather than console.log().


Look at these 2 functions:

function add(x, y) {
  return x + y;
}

var result1 = add(1, 1);
function logAdd(x, y) {
  return console.log(x + y);
}

var result2 = logAdd(1, 1);
  • result1 will store 2, but nothing is in the console yet. You could do console.log(result1) to see it.
  • result2 will store undefined, but you will see 2 in the console. The problem is if you wanted to use the output later; you probably want to use the number 2, not undefined.

The trick is, console.log() doesn’t return the thing it prints. It returns the value undefined. The words that get sent to the console are a separate action from “returning”.

You can imagine the code simplifying like a math equation:

10 * (3 - 1);
10 * (2);
20;

In this example, (3 - 1) simplifies, or “evaluates”, to 2.


Look at what happens as we evaluate the following code:

console.log(10 * console.log(3 - 1));
  • 3 - 1 is 2
console.log(10 * console.log(2));
  • console.log(2) will log 2 to the console and then evaluate to undefined.
console.log(10 * undefined);

Uh oh, 10 * undefined is not a number. This is the limitation of console.log().

  • If you have a value and you want to see it on the screen now, use console.log() on the value
  • If you have a function that has evaluated its final output, use return to output that value.

–Frankie

1 Like

First off, thank you very much for your reply. I now have a better understanding of the use of return and functions themselves. I also appreciate the depth at which you explained the different scenarios.
For what my calculator was looking back on it now, it seems like my code was fairly compact compared to the result1 example understanding that nothing was even logged to the console yet. I do like the setup in that example, because it brings together the x and y along with the function of adding,subtracting,etc on one line instead of manually changing the x and y values and the using console.log (add)for example to print the value of the variable add. I plan on trying to clean up the seemingly excessive “var” usage. I believe I remember reading about a way to do so somewhere in grasshopper already. My ultimate goal in this project is to create a functioning multivalue (more than 2 lol) calculator. What might the maximum number of characters able to be used in a single set of code within playground for a snippet? I sincerely thank you for your help.