What is the use of console.log
?
Please explain how to use it in JavaScript, with a code example.
In early days JS debugging was performed through alert()
function - now it is an obsolete practice.
The console.log()
is a function that writes a message to log on the debugging console, such as Webkit or Firebug. In a browser you will not see anything on the screen. It logs a message to a debugging console. It is only available in Firefox with Firebug and in Webkit based browsers (Chrome and Safari). It does not work well in all IE releases.
The console object is an extension to the DOM.
The console.log()
should be used in code only during development and debugging.
It’s considered bad practice that someone leaves console.log()
in the javascript file on the production server.
console.log
specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code. Its asynchronous nature means that the logged values don't necessarily represent the value when the method was called.
In short: log errors with console.log
(if available), then fix the errors using your debugger of choice: Firebug, WebKit Developer Tools (built-in to Safari and Chrome), IE Developer Tools or Visual Studio.
If your browser supports debugging, you can use the console.log() method to display JavaScript values.
Activate debugging in your browser with F12, and select "Console" in the debugger menu.
Console in JavaScript. Try to fix, or "debug," a non-functioning JavaScript program, and practice using the console.log() command. There are shortcuts that is going to help you to access to the JavaScript console, based on the browser that you are using:
Chrome Console Keyboard Shortcuts
Windows: Ctrl + Shift + J
Mac: Cmd + Option + J
Firefox Console Keyboard Shortcuts
Windows: Ctrl + Shift + K
Mac: Cmd + Option + K
Internet Explorer Console Keyboard Shortcuts
F12 key
Safari Console Keyboard Shortcuts
Cmd + Option + C
Apart from the usages mentioned above, console.log
can also print to the terminal in node.js
. A server created with express (for eg.) can use console.log
to write to the output logger file.