JavaScript Getting started with JavaScript Using console.log()

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Introduction

All modern web browsers, NodeJs 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:

Console Log Output in Google Chrome

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:

console.log() can be used with variables

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:

Console Concat


Placeholders

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

var greet = "Hello", who = "World";
console.log("%s, %s!", greet, who);

This will log the following to the console:

enter image description here


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:

Logged object in 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);

This will log the following to the console:

enter image description here


End Note

For more information on the capabilities of the console, see the Console topic.



Got any JavaScript Question?