Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Emeruche Ikenna
Emeruche Ikenna

Posted on • Edited on

     

JavaScript Console API and Methods

originally published at myblog.

As a JavaScript engineer, I have used theconsole.log() method more times thanthe number of people killed in Game Of Thrones up to the 7th season — well, maybe not that much.

The point, is that much like many other (newbie) JS coders, I pretty much knewlog() as the only method on the JavaScriptconsole object.

Yes, it is an object.
You can verify this by opening up your browser console and runningtypeof(console) and you should get “object” returned back.

Now that we have proven it is an object, like all other objects, it has many other methods in it apart fromlog().

“Why is it so important knowing these other methods?”, you may ask. Well, although you might just go on using thelog method to debug your code, learning about and using other methods helps in better representation and easier debugging. Andhey!, why not learn more to help us combat our common enemy — bugs. Besides, you dunno what your next job interviewer has under their sleeves.

Let’s get started, shall we?

Hopefully, your browser console is still up and running, if not open it up again, and never close it till we are done with this, as we will get back to them occasionally.

To view other methods on the console, try runningconsole.log(console) — the irony! The data below should be returned to us:

console{debug:ƒ,error:ƒ,info:ƒ,log:ƒ,warn:ƒ,}assert:ƒassert()clear:ƒclear()context:ƒcontext()count:ƒcount()countReset:ƒcountReset()debug:ƒdebug()dir:ƒdir()dirxml:ƒdirxml()error:ƒerror()group:ƒgroup()groupCollapsed:ƒgroupCollapsed()groupEnd:ƒgroupEnd()info:ƒinfo()log:ƒlog()memory:(...)profile:ƒprofile()profileEnd:ƒprofileEnd()table:ƒtable()time:ƒtime()timeEnd:ƒtimeEnd()timeLog:ƒtimeLog()timeStamp:ƒtimeStamp()trace:ƒtrace()warn:ƒwarn()Symbol(Symbol.toStringTag):"Object"getmemory:ƒ()setmemory:ƒ()__proto__:Object
Enter fullscreen modeExit fullscreen mode

This gives us so much more methods than we (rather, I) ever knew existed on the console. And like every other numerous lists, we will pick our most important ones.

console.assert()

The simplest case of using theassert() method, is when we want to display something on the console only and only if the assertion passed into the method is false. If by any means the assertion passes, nothing happens, or you get anundefined if you are using a browser console. To see this in action, pull up your console if not open (PUYCINO — this is not a real thing) and run the following code:

varx=21;console.assert(x%2===0,'oops! x is not divisible by 2');// or alternativelyvarerrMsg='oops! x is not divisible by 2';console.assert(x%2===0,errMsg);
Enter fullscreen modeExit fullscreen mode

You should get an assertion error with the error message printed to the console. Try changingx to 20 or any other even number and run the assert code again, this time nothing happens.

console.clear()

This method is simple enough. Runningconsole.clear() just clears the console and displaysConsole was cleared message (as if we cannot see it has been cleared). Run this code whenever you feel your console is all clogged up and you need room.

console.dir() and console.dirxml()

This method helps us to print out to the console all the properties (methods) of any valid JavaScript object passed into it. Remember when we said — and proved — thatconsole was an object. Now lets use it as an argument in theconsole.dir() method. PUYCINO and run the codeconsole.dir(console) and a familiar output will be displayed. You can also tryconsole.dir(window) to view the properties on the native Window object. And this will come in handy someday, you’ll see!

dirxml is almost similar todir with very small and insignificant differences.

console.error()

This displays content as an error — red highlight, light red background and a red error (x) sign by the side. All features to let you know that what is being displayed is an error. Try runningconsole.error('This is a typical error') and see what I mean.

The use case for this is when you are expecting an error in your code. Example, during a .catch block of an API call that returns a Promise.

console.group(), console.groupCollapsed() and console.groupEnd()

These methods are used to group together blocks of code or similarwhatever it is you’re trying to display to the console.
group() signifies the start of the group. It accepts an optionallabel as an argument. The label serves as, well, the label for the group.

groupEnd() marks the end of a group.

groupCollapsed() works likegroup() but while all items ingroup() is automatically all listed out,groupCollapsed() displays them in a collapsed manner, you will have to manually click on a “dropdown” list beside it to list them all out.

Let us see this in action. PUYCINO and paste the following:

console.group('My fav tech tools')// Here, 'my fav tech tools' is the label for my groupconsole.log('React')console.log('Twitter Bootstrap')console.log('Django')console.log('Django REST')console.log('Axios')console.groupEnd()//ends the group
Enter fullscreen modeExit fullscreen mode

Groups can also be nested into another group. Let’s see how this andgroupCollapsed() works:

console.groupCollapsed('My fav languages and tools')console.group('JavaScript')//nests in JavaScript groupconsole.log('React')console.log('Redux')console.log('Twitter Bootstrap')console.groupEnd()//exits nested group for JavaScriptconsole.groupCollapsed('Python')//nests in a collapsed Python groupconsole.log('Django')console.log('Django REST')console.groupEnd()//exits nested group for Pythonconsole.groupEnd()//exits all groups
Enter fullscreen modeExit fullscreen mode

As you can see, at first the displayed groups are collapsed and you will have to expand them manually. Next, you can see we nested in two more groups: JavaScript and Python.

Always remember to exit each nested group withgroupEnd() as pointed out above.

console.log()

I think we all are familiar with this. So no need to waste time. It basically just prints out something to the console without any level of warning or danger.

console.table()

This displays data in a tabular format. It takes in a compulsorydata which must be an array or object — passing in a string does not work — and an optionalcolumns as parameter.
Let us see this in action. Again, PUYCINO (hey, by now there is no more need to include this). Paste in the following:

varnations=['Nigeria','USA','Canada','Algeria'];console.table(nations)
Enter fullscreen modeExit fullscreen mode

This should print the data out in a tabular form with(index) andvalue columns. Using arrays, the(index) column is auto filled with the index of the instance. To specify what should be used as the table’s index, pass in objects instead. Here, the(index) column will be filled by thekeys of the object while the value will be filled by thevalues of the object. Try below:

varnationsCurrency={USA:'dollars',Nigeria:'naira',France:'franc'}console.table(nationsCurrency)
Enter fullscreen modeExit fullscreen mode

console.time() and console.timeEnd()

time() starts a timer you can use to track how long an operation takes. It takes in an optionallabel as argument. Calling timeEnd() with the samelabel ends the timer and ouputs the time (in miliseconds) that has elapsed sincetime() was called and code betweentime() andtimeEnd() has executed.

console.time('test')letmult=(2000*4444);mult*222;console.timeEnd('test')
Enter fullscreen modeExit fullscreen mode

Best use case for this is to compare which two similar functions or logic is faster. Example, the code below compares the speed of execution offor andwhile loops.

console.time("test for loop");for(i=0;i<100000;i++){console.log(i)}console.timeEnd("test for loop");console.time("test while loop");while(i<1000000){i++}console.timeEnd("test while loop");
Enter fullscreen modeExit fullscreen mode

From running the above code, we can effectively see that thefor loop is faster than thewhile.

console.warn()

Outputs a warning message to the browser console. It displays the data in a light yellow background with a warning icon by the side. Try it:

console.warn("GOT is hugely graphical and full of violent. Watch at your own discretion.")
Enter fullscreen modeExit fullscreen mode

We are done with the important methods. Hopefully by now you will have lessconsole.log() lines during debugging sessions.

Or maybe not, either way thanks for getting this far.

Valar Morghulis!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Blockchain (Solidity) and Frontend software engineer.
  • Location
    Nigeria
  • Work
    Software Engineer II at Crossover
  • Joined

More fromEmeruche Ikenna

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp