简体   繁体   中英

printing the result of the function to the console.

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM