The console.log() is a basic JavaScript function that is used to display or print any message to the debugger’s console. The message can be any variable defined before (including arrays, objects, and so on) or any string. The console.log() is commonly used for testing purposes during the development phase.
Syntax
An example using a variable defined before in it.
console.log(fullName);
Output
How it works
The log() is a method in the web API “API Console” which is available in almost every browser and JavaScript editor, the purpose of this method is to display anything passed into it using the parameters to the console panel and to access this log() method we use the console object with a dot-operator.
Console Object Methods
The console object is used with a “dot-operator” to utilize quite useful predefined methods. Some examples of these methods would be as follows:
assert(): Writes an error message to the console if the assertion is false
clear(): Clears the console terminal / panel
time(): Starts a timer (can track how long an operation takes)
Parameters
It accepts a parameter which can be a message (string) or any object.
Return Value
The return type is the same as the parameter that is passed into it.
Examples using different types of Parameters
Now, we are going to use different types of parameters to show the working of the console.log() method.
Using a String and number: First up, is an example with a simple numeric value and a string as its parameter.
console.log(2);
Output
The output can be seen in the image below:
Using an Array: Next up, it would be an example using an array of String objects.
console.log(arr);
Output
The output can be seen in the image below:
Using an object: Now that we have used a simple numeric value, a string, and even an array of strings, it’s time to move on to Objects.
console.log(myObj);
Output
The output of using the console.log() with an object as its parameter is as follows:
Conclusion
JavaScript is becoming the most widely used scripting\ programming language in the world and if we want to become familiar with the modern-day programming sensation then we should know how various methods work in JavaScript.
We have learned what console.log is, its syntax, usage, parameters, return values along with examples. We also learned how a console.log works by explaining what the log() method actually is and how the “console” object is used to call different methods defined in the “API CONSOLE” from the WEB API which is built into different browsers and code editors.