Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to use console.log in javascript?

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

How to use console.log in javascript?

Post by admin » Sun Oct 20, 2019 1:02 am

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 :

Code: Select all

console.log("Hello, World!");
This will log the following to the console:
Image

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);
This will log the following to the console:
Image
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);
This will log the following to the console:
Image

Placeholders
You can use console.log() in combination with placeholders:

Code: Select all

var greet = "Hello", who = "World";
console.log("%s, %s!", greet, who);
This will log the following to the console:
Image

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'
});
This will log the following to the console:
Image

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);
This will log the following to the console:
Image

Post Reply