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!


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading