1
var square = function(x){
   return x*x;
}
square(10);//100 

var square = function(x){
  var total = x*x;
  console.log(total);
}
square(10);//second way(probably wrong)

I was reviewing what I once wrote when passing the JS-track on codecademy.com. The task is incredibly simple - write a function that just squares a number and prints it in the console.
I did it the second way (using total variable inside the function block). Now I would do it the first way. Both seem to work. But is the second one really correct?

4
  • 2
    Well, in your second example the function doesn't return anything so it is pretty useless. Logging to the console is only used for debugging. I guess what you want in the first case is console.log(square(10)). Commented Jan 9, 2016 at 20:10
  • @Felix Kling, thank you very much. One more question. When I write console.log(square(10)) it returns 100 and then undefined. Why is that? Commented Jan 9, 2016 at 20:15
  • console.log prints the value to the console and doesn't return anything, hence the implicit return value of undefined. Commented Jan 9, 2016 at 20:22
  • Could you please accept one of the answers if it fulfills the question. Commented Jan 9, 2016 at 21:38

3 Answers 3

1

The second one is still correct if you want it printed to the console. In a real-world situation, you'd want the result returned to the calling function so it can do other things with the value and then it would fail, since your function does not return anything.

Sign up to request clarification or add additional context in comments.

Comments

1

Well the first one actually calculates the square root, so it's a usable function. The second one just prints it to the console - so I'd stick with the first one.

Comments

-1

Both methods work at correctly squaring the input, and there's nothing wrong syntactically in either function.

However, there is a problem with practicality. The first function only calculates the square of the input without giving out any return, or output, and therefore is not useful.

The second function is more practical because it logs the square of the input into the console, and therefore has an output, which in turn can be useful.

1 Comment

I think you have it the wrong way around. The first function does return something. The second one doesn't return anything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.