Using console.log()
Introduction
All modern web browsers, Node.js as well as almost every other JavaScript environments support writing messages to a console using a suite of logging methods. The most common of these methods is console.log().
In a browser environment, the console.log() function is predominantly used for debugging purposes.
Getting Started
Open up the JavaScript Console in your browser, type the following, and press Enter :
console.log("Hello, World!");
This will log the following to the console:
In the example above, the console.log() function prints Hello, World! to the console and returns undefined (shown above in the console output window). This is because console.log() has no explicit return value.
Logging variables
console.log() can be used to log variables of any kind; not only strings. Just pass in the variable that you want to be displayed in the console, for example:
var foo = "bar";
console.log(foo);
This will log the following to the console:
If you want to log two or more values, simply separate them with commas. Spaces will be automatically added between each argument during concatenation:
var thisVar = 'first value';
var thatVar = 'second value';
console.log("thisVar:", thisVar, "and thatVar:", thatVar);
This will log the following to the console:
Logging Objects
Below we see the result of logging an object. This is often useful for logging JSON responses from API calls.
console.log({
'Email': '',
'Groups': {},
'Id': 33,
'IsHiddenInUI': false,
'IsSiteAdmin': false,
'LoginName': 'i:0#.w|virtualdomain\\user2', 'PrincipalType': 1,
'Title': 'user2'
});
This will log the following to the console:
Logging HTML elements
You have the ability to log any element which exists within the DOM. In this case we log the body element:
console.log(document.body);