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 :
Code: Select all
console.log("Hello, World!");

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:
Code: Select all
var foo = "bar";
console.log(foo);

If you want to log two or more values, simply separate them with commas. Spaces will be automatically added
between each argument during concatenation:
Code: Select all
var thisVar = 'first value';
var thatVar = 'second value';
console.log("thisVar:", thisVar, "and thatVar:", thatVar);

Placeholders
You can use console.log() in combination with placeholders:
Code: Select all
var greet = "Hello", who = "World";
console.log("%s, %s!", greet, who);

Logging Objects
Below we see the result of logging an object. This is often useful for logging JSON responses from API calls.
Code: Select all
console.log({
'Email': '',
'Groups': {},
'Id': 33,
'IsHiddenInUI': false,
'IsSiteAdmin': false,
'LoginName': 'i:0#.w|virtualdomain\\user2',
'PrincipalType': 1,
'Title': 'user2'
});

Logging HTML elements
You have the ability to log any element which exists within the DOM. In this case we log the body element:
Code: Select all
console.log(document.body);
