Mar 14, 2017

Mastering the Console in Javascript

Javascript has many ways to debug what it’s going on under the...

Javascript has many ways to debug what it’s going on under the hook. Every modern browser has a built-in Javascript Debugger, for example in Chrome we have the “Chrome Developer Tools” and in Firefox, “The Web Console”.

It doesn’t matter the name, each of them does the same job: help you to debug your site or web app so you can create great and clean code. This is such a powerful tool!

Debugging is not an easy task and as a web developer you might have written several javascript files or maybe inline javascript inside an HTML file but I’m pretty sure that you have used console.log(var) at least once.

Console is an object which you can accessed from any global object.

In this post you’re going to learn how to debug the web using the methods provide by the console.

Developer Tools

The Developer Tools will help you to debug your web application. It provides deep access to the internal of the browser and your site. With DevTools you can iterate, debug and profile your site.

I’m going to give you a nice example:

QUESTION GAME:

A good developer tests its projects, we’re in 2017, we live in a mobile era where everyone has a phone and surfs the web in it. You might want to know what’s the behaviour of your site in a 3G connection but sadly right now you do not have a phone. What would yo do?

  1. Grab your friend’s phone
  2. Use DevTools

If you chose the option number two, you have won!!! 🎉.

You don’t need any phone to check how your site goes in a 3G connection or maybe in a 2G network, you have DevTools! You can simulate one, I’m not going to explain how you can do this (it’s pretty simple) because it’s not the scope of this post but I’m going to give you a link so you can read more about this: Link

How can I open DevTools?

Nice question! It depends on your browser but here it is:

(If you already know this, you can skip this)

Google Chrome
  • Select More Tools > Developer Tools from the Chrome Menu.
  • Right-click on a page element and select Inspect
  • Use the keyboard shortcuts Ctrl + Shift + I on Windows or Cmd + Opt + I on Mac or F12
Firefox
  • Select “Web Console” from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
  • Use the keyboard shortcuts Ctrl + Shift + K or Cmd + Opt + K on Mac
  • Right-click on a page element and select Inspect Element
Opera
  • Use the keyboard shortcuts Ctrl + Shift + I on Windows or Cmd + Opt + I on Mac
  • You can target a specific element by right-clicking in the page and selecting “Inspect Element”.
Microsoft Edge
  • Use the keyboard shortcut F12
  • Select F12 Dev Tools from the Edge Menu.
  • Right-click on a page element and select Inspect Element
Safari
  1. To start using Web Inspector, you must first enable the Develop menu. To do so, enable the “Show Develop menu in menu bar” setting found in Safari’s preferences under the Advanced pane
  2. You can then access Web Inspector through the Develop menu that appears in the menubar, or by pressing Command-Option-I. You can also add the Web Inspector toolbar item to Safari’s toolbar by selecting View > Customize Toolbar.
Internet Explorer
  • Press F12 or click Developer Tools from the Tools menu.
  • Right-click on a page element and select Inspect Element

Awesome! Now that you know how to open DevTools, open it and switch to the console by clicking the Console tab at the top of the window.

Let’s test the console

Write this in the console:


console.log('Hello World');

Awesome!! You should see that Hello World is printed in the console. Nice job!

You might wondering why console.log() prints the expected value and then undefined. The console always prints the result of evaluating an expression.

console.log() doesn’t explicity return something and that’s why the result of the evaluation of that expression is undefined. The same happens when you assign a value to a variable.

Expressions containing a mathematical operator like + or - produce a value which is printed to the console instead of undefined. Try 2 + 2 and you will get 2, try var x = 4; and you will get undefined.

In the console the icon represents your message to the console and represents the response from the console.

Let’s take a look at all the console methods you can use.

Logging text to the console:

1. console.log(obj1 [, obj2, ..., objN]);

This is the most common way to log text or data in the console. You can pass as parameters a list of objects (strings, numbers, variables). The string representations of each of those objects will get printed in the console in the same order listed.


const name = "Fede Guzmán"
const age = 21;
const dogs = {name: "Rita", age: 8};

console.log(name, age, dogs);

The output will look like this:


Fede Guzmán 21 Object {name: "Rita", age: 8}

Using string substitutions

You can pass a string to the console using String substitutions, like this:


const age = 19;

console.log("Hey, I'm %s and I'm %i years old, next year I'll be %i", "Fede", age, age+1);

These are string substitutions that allow you to define the format of the objects:

%s → String
%d or %i → Integer
%f → Floating-point value
%O → Object

Let's put some colors and style to the console!

There’s one more string substition in the list and it’s %c. You can use it to style the console using CSS.


console.log("%cToday is a sunny day!!", 'font-size: 50px; background-color: gold; border-radius: 5px; font-family: "Arial Black"; color: #000; padding: 5px;');


The output will look like this:

Not all of the CSS properties are supported.

TIP:

It’s very common to use console.log() to debug your site and sometimes you log several variables there like this:


const x = 500;
const y = window.pageYOffset;

console.log(x, y);

but this is what the output will look like:

500 0

You might get confuse about which one is x or which one is y but there’s a solution here, convert them to an object!

console.log({x,y});

This output will look like this:

Object {x: 500, y: 0}

Variants of console.log()

2. console.info(obj1 [, obj2, ..., objN]);

Outputs an informational message to the console. An icon is displayed next to the message.


console.info("The request was successful");

3. console.error(obj1 [, obj2, ..., objN]);

Outputs an error message to the console. An icon and a red background is displayed in the message.


console.error("The request failed");

4. console.warn(obj1 [, obj2, ..., objN]);

Outputs a warning message to the console. An icon and a light yellow background is displayed in the message.


console.warn("The request might failed because you did not enter your security ID.");

Other methods

5. console.assert(obj1 [, obj2, ..., objN]);

The output is an error message if the assertion is false. If it’s true nothing happens!


function canDrinkAlcohol(age){
    return age >= 18
}

const can = canDrinkAlcohol(17);

console.assert(can);

6. console.clear();

This one is really simple. It cleans the console! The content will be replaced with a message like “Console was cleared”.

console.clear();

7. console.count([label]);

The output is an integer and it refers as the number of times it has been called.

No Label

let name = "";
let age;

function canDrinkAlcohol(){
    console.count();
    if(age >= 18){
       return `${name} can drink alcohol`;
    } 
    return `${name} CAN'T drink alcohol. Bye`;
}

name = "Gloria Delgado";
age = 44;
canDrinkAlcohol(); // 1
name = "Claire Dunphy";
age = 47;
canDrinkAlcohol(); //2
name = "Alex Dunphy";
age = 16;
canDrinkAlcohol(); //3
name = "Luke Dunphy";
age = 14;
canDrinkAlcohol(); //4
console.count(); // This is an indepedent event.

The output will look like this:

: 1
: 2
: 3
: 4
: 1

With Label

With a label we mantain separate the counting based only on the value of the label.

let name = "";
let age;

function canDrinkAlcohol(){
    console.count(name);
    if(age >= 18){
       return `${name} can drink alcohol`;
    } 
    return `${name} CAN'T drink alcohol. Bye`;
}

name = "Gloria Delgado";
age = 44;
canDrinkAlcohol(); //1
name = "Alex Dunphy";
age = 16;
canDrinkAlcohol(); //1
name = "Luke Dunphy";
age = 14;
canDrinkAlcohol(); //1
name = "Luke Dunphy";
age = 14;
canDrinkAlcohol();//2
name = "Luke Dunphy";
age = 14;
canDrinkAlcohol(); //3
console.count("Luke Dunphy"); // 4

The output will look like this:

Gloria Delgado: 1
Alex Dunphy: 1
Luke Dunphy: 1
Luke Dunphy: 2
Luke Dunphy: 3
Luke Dunphy: 4

8. console.dir(obj);

Display a list of the properties of a Javascript Object.

console.dir(document);

Comparing console.dir() with console.log()

The difference between console.log() and console.dir() is that log prints out a toString representation whereas dir prints out a tree.

9. console.group(obj);

Creates a group of logs in the console which indents all following outputs by levels until console.groupEnd() is called.

10. console.table(obj);

With this function you can display a tabular data as a table. The argument must be an array or an object. The first column will be the index.

You can select columns by using the optional parameter where you can pass an array of column names.

For example, sometimes you have a javascript object or a JSON like this:

const series = [  
   {  
      "Title":"Grey's Anatomy",
      "Genre":"Drama, Romance",
      "Plot":"A drama centered on the personal and professional lives of five surgical interns and their supervisors.",
      "Actors":"Ellen Pompeo, Justin Chambers, Chandra Wilson, James Pickens Jr."
   },
   {  
      "Title":"Riverdale",
      "Genre":"Crime, Drama, Mystery",
      "Actors":"K.J. Apa, Lili Reinhart, Camila Mendes, Cole Sprouse",
      "Plot":"A subversive take on Archie and his friends, exploring small town life, the darkness and weirdness bubbling beneath Riverdale's wholesome facade."
   },
   {  
      "Title":"Suits",
      "Genre":"Comedy, Drama",
      "Actors":"Gabriel Macht, Patrick J. Adams, Rick Hoffman, Meghan Markle",
      "Plot":"On the run from a drug deal gone bad, Mike Ross, a brilliant college-dropout, finds himself a job working with Harvey Specter, one of New York City's best lawyers."
   }
];
console.table(series);
console.table(series, ['Title', 'Plot']);

The output will look like this:

11. console.time(label);

Starts a timer so you can track how long an operation takes. You give it a label and when you call console.timeEnd(label) the console will output the time in miliseconds.

console.time('fe');

fetch('http://swapi.co/api/people/1/?format=json')
    .then(json => {
        console.timeEnd('fe');
        console.log(json)
});
fe: 252.980224609375ms

Another example (might take a few seconds):

let c = 0;
console.time('sum');

for(let i = 0; i <= 7e8; i++){
    c += (i * 2) / 3;
}

console.timeEnd('sum');
console.log(c);

12. console.trace();

Print the call path taken to reach the point at which you call console.trace().

function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();

Example from MDN

Summary

In this post you learned about the several console methods you can use to debug your websites. I recommend to read the Console Standard to dive in and discover more about what the Console API can offer you.

What do you use to debug your web sites? Feel share to share in the comments!