Reputation: 10235
When I fire up node.js in the terminal and run 4 + 4
, it outputs 8
as expected. However, when I run the same code but from a file... I get no output unless I use console.log
!?
console.log
was code for the browser... Why is it running in node.js? Yes, I know that node.js is built on the same engine that chrome was built on... But still, they are two different products. Doesn't console.log
make more sense on the browser side of things than node.js?Much appreciated.
Upvotes: 2
Views: 2698
Reputation: 1413
Talking about computers, console
is a wide concept used main to refer to a terminal where you have an input and output sources. It is likewise your OS shell terminal. So, in Javascript, the console
object kind of represents the terminal where it's running your code. Definitely, it's not intended to be a browser thing
.
Anyway, when you are running your Javascript code on a terminal prompt, you are inputing and outputting every command and return. Usually it will read your input and print the return value. When you execute a code, from a file, if you want it to read from the running terminal, or to print on it, you must tell your code to do so. This is because when you run a code and you need to tel it to print on your console (console.log
) if you want it to do so. So, you tell it to take the return of the expression and print on the console. When you don't tell it to do so, it will return the evaluated expression but it won't print, so you can't see it.
Hope it is of some help.
Upvotes: 6
Reputation: 269
Well the console.log
function is used as a basic function to literally ,as the name suggests, to log something to the console . When running in an integrated environment such as node.js , it give you an easy to use single-to-multi line execution ,every output is flushed out to console automatically. On the other hand, typing the same code in a JS file t,we are not giving any particular information to the script that it needs to output the answer
For Example:
App.js
4+4
If we run it in terminal output will be nothing, but if we use
app_console.js
console.log(4+4)
and run it as
$ node app_console.js
it will result as 4
because we are explicitly telling the engine to output it. Several other languages uses they execution in-line console such as Pyshell for Python
Upvotes: 1