How to save time typing console.log() statements in Javascript?

For a javascript developer , console.log() statement is a great companion.

It helps debugging issues fast.

But typing this statement can be time consuming.

There are two tricks to help in reducing time , typing this statement.

Trick 1: Enclose variables to print in curly braces {} .

Let’s say you want to print the input to a text box to the console.

Below is a sample javascript code:

var input = document.getElementById("myinput").value;

To print the input to the console you may want to do something like this :

console.log("input",input);

The first keyword helps in mapping the data printed on the console .

In the console you will see the below output:

You can avoid printing the first keyword by including input variable in curly braces like this:

console.log({input});

DevTools automatically creates a mapping keyword on seeing the curly braces!

Below is the output on the console:

Trick 2: Create a variable globally and assign the function console.log() to it.

Create a global variable like this :

var l = function(message){ return console.log(message);};

and place it globally (outside the other functions).

Now instead of using console.log() to print messages , you can simple use l() like this :

l({input});

This prints the same input as above.

Here is the entire code with the different styles:




<html>



<body>


<input id= "myinput" />

<button onclick="log()">Click me</button>


<script type ="text/javascript">

var l = function(message){ return console.log(message);};

function log(){

var input = document.getElementById("myinput").value;

console.log("input",input);
console.log({input});

l({input});
}

</script>
</body>

</html>

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s