When I say JavaScript console methods, the one and only thing that hit most of our mind is console.log() and we use it a lot and only that some might be familiar with error() and debug(). Did you ever think of checking if there are any other methods available in console other than log? Most of us don't do that, but knowing those methods might have saved lot of our development time. In this post I will show you some of the console methods which will be very useful in our day to day coding.
Note: In chrome this log will print as an error with message saying "Assertion failed:" with the log_message passed. In FireFox its a normal log message.
Log based on condition
console.assert(assertion, log_message);To print something on the console only if the assertion failed - assertion can be any expression which returns a boolean.
Note: In chrome this log will print as an error with message saying "Assertion failed:" with the log_message passed. In FireFox its a normal log message.
Log number of occurrence
console.count([label]);If we want to count something, it may be a click, may be a callback, or event triggers. We don't need to create a var and increment and then log. We can simply use console.count('my_clicks') and console will do the counts for you and print the same. Wow! Nice right? But see below for another handy method which we missed.
Log time taken
console.time([label]); //do_some_work console.timeEnd([label]);An easy way for developers to see how much time a logic is running. Given a label name this method will print the amount of time taken in milliseconds between the time() and timeEnd() method for that particular label.
Trace who triggered this function
console.trace();Did you ever care to find which action is triggering a particular action or event? If yes, trace() is a wonderful console method which will give you all the levels of trace till the line where you called trace() method. This will give the file names with line numbers where the trigger came from. A big time saver right?
Do you know that you can use c like syntax in console messages?
var test = ['one','two'] console.log("This is an object %o and its length is %d", test, test.length);
List of substitutions you can use:
- %o or %O : Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
- %d or %i : Outputs an integer. Number formatting is supported, for example console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
- %s : Outputs a string.
- %f : Outputs a floating-point value. Formatting is supported.
If you find some other useful methods, let me know in the comments section and check the source link for some more methods, details and browser support.
Source: https://developer.mozilla.org/en-US/docs/Web/API/console
Source: https://developer.mozilla.org/en-US/docs/Web/API/console
How you create these code snippets?
ReplyDeletethanks you sir valuable information.
ReplyDelete