In this section, we will learn what the console log() method is and how to use it in JavaScript.
Logging in JavaScript
In programming languages like JavaScript, when creating a program, we need to monitor every step and make sure they are running accurately.
One way to run this monitoring is by sending messages from different sections of a program to a place like a file or, in case of JavaScript, to a browser console.
This is called logging.
After sending messages to a browser console, developers can check those logs and analyze to see if the program is working correctly or there are bugs to be fixed, etc.
JavaScript Console log() Method
The `log()` method in JavaScript is a way of sending messages that are considered as log to a browser console.
Console log() Method Syntax:
console.log(message)
Console log() Method Parameter:
The `log()` method takes a variable number of arguments and these are basically the messages (logs) that we want to send to a browser console.
Console log() Method Return Value:
The return value of this method is undefined.
Example: JavaScript print to console
console.log("This is a message coming from the log method."); const name = "John Doe"; console.log(name);
Output:
This is a message coming from the log method. John Doe
Example: JavaScript write in console
console.log("This is a message coming from the log method."); const name = "John Doe"; console.log(name, "Omid Dehghan");
Output:
This is a message coming from the log method. John Doe Omid Dehghan
Example: JavaScript output to console
const obj = { name: "John Doe" } console.log(obj);
Output:
{name: 'John Doe'}
Here the argument of the `log()` method is an object and as you check the browser console, you’ll see that the message is exactly the content of the object.