
A JavaScript egyik legalapvetőbb hibakereső eszköze console.log()
. A console
már számos más hasznos módszer, ami növelheti a fejlesztő hibakeresés eszközkészlet.
A console
következő feladatok végrehajtására használhatja:
- Adjon ki egy időzítőt az egyszerű összehasonlításhoz
- Táblázat kiadása egy tömb vagy objektum könnyen olvasható formátumban történő megjelenítéséhez
- Alkalmazzon színt és más stílusbeállításokat a kimenetre a CSS segítségével
A konzolobjektum
Az console
objektum hozzáférést biztosít a böngésző konzoljához. Ez lehetővé teszi olyan karakterláncok, tömbök és objektumok kimenetét, amelyek segítenek a kód hibakeresésében. Ez console
az window
objektum része , és a böngésző objektum modellje (BOM) szolgáltatja.
console
Kétféleképpen férhetünk hozzá a :
window.console.log('This works')
console.log('So does this')
A második lehetőség alapvetően az előbbire utal, így az utóbbit fogjuk használni a billentyűleütések mentésére.
Egy rövid megjegyzés a BOM-ról: nincs meghatározva szabványa, ezért minden böngésző kissé eltérő módon hajtja végre. Az összes példámat teszteltem mind a Chrome-ban, mind a Firefox-ban, de a kimenet a böngészőjétől függően eltérő lehet.
Szöveg kiadása

Az console
objektum leggyakoribb eleme az console.log
. A legtöbb esetben a feladat elvégzéséhez használja.
Az üzenetnek a konzolra történő küldésének négy különböző módja van:
log
info
warn
error
Mind a négy ugyanúgy működik. Csak annyit tesz, hogy egy vagy több argumentumot átad a kiválasztott módszernek. Ezután egy másik ikont jelenít meg a naplózási szint jelzésére. Az alábbi példákban láthatja a különbséget egy információs szintű napló és egy figyelmeztető / hibaszintű napló között.


Lehet, hogy észrevette a hibanapló üzenetét - mutatósabb, mint a többi. Vörös hátteret és veremnyomot is megjelenít, hol info
és hol warn
nem. Bár warn
sárga háttérrel rendelkezik a Chrome-ban.
Ezek a vizuális különbségek segítenek abban az esetben, ha gyors pillantásra fel kell derítenie a konzol hibáit vagy figyelmeztetéseit. Győződjön meg arról, hogy eltávolítják őket a gyártásra kész alkalmazások számára, hacsak nem azért vannak, hogy figyelmeztessék a többi fejlesztőt arra, hogy valamit rosszul csinálnak a kóddal.
Karakterlánc-cserék
Ez a technika egy helyettesítőt használ egy karakterláncban, amelyet a metódusnak átadott többi argumentum (ok) helyettesít. Például:
Bemenet :console.log('string %s', 'substitutions')
Kimenet :string substitutions
Ez a vessző utáni %s
második argumentum helyőrzője 'substitutions'
. Bármilyen karakterlánc, egész szám vagy tömb átalakul karakterláncsá, és felváltja a karakterláncot %s
. Ha elhalad egy objektum mellett, az megjelenik [object Object]
.
Ha át akar adni egy objektumot, akkor a %o
vagy %O
helyett kell használnia %s
.
console.log('this is an object %o', { obj: { obj2: 'hello' }})

Számok
A karakterlánc-helyettesítés egész számokkal és lebegőpontos értékekkel használható:
%i
vagy%d
egész számokra,%f
lebegőpontokra.
Bemenet :console.log('int: %d, floating-point: %f', 1, 1.5)
Kimenet :int: 1, floating-point: 1.500000
Az úszók úgy formázhatók, hogy csak egy számjegyet jelenítsenek meg a tizedespont után %.1f
. Megteheti, %.nf
hogy n számjegyet tizedesjegy után jelenítsen meg.
If we formatted the above example to display one digit after the decimal point for the floating-point number, it would look like this:
Input: console.log('int: %d, floating-point: %.1f', 1, 1.5)
Output:int: 1, floating-point: 1.5
Formatting specifiers
%s
| replaces an element with a string%(d|i)
| replaces an element with an integer%f
| replaces an element with a float%(o|O)
| element is displayed as an object.%c
| Applies the provided CSS
String Templates
With the advent of ES6, template literals are an alternative to substitutions or concatenation. They use backticks (``) instead of quotation marks, and variables go inside ${}
:
const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions
Objects display as [object Object]
in template literals, so you’ll need to use substitution with %o
or %O
to see the details, or log it separately by itself.
Using substitutions or templates creates code that’s easier to read compared to using string concatenation: console.log('hello' + str + '!');
.
Pretty color interlude!
Now it is time for something a bit more fun and colorful!
It is time to make our console
pop with different colors with string substitutions.
I will be using a mocked Ajax example that give us both a success (in green) and failure (in red) to display. Here’s the output and code:

const success = [ 'background: green', 'color: white', 'display: block', 'text-align: center'].join(';');
const failure = [ 'background: red', 'color: white', 'display: block', 'text-align: center'].join(';');
console.info('%c /dancing/bears was Successful!', success);console.log({data: { name: 'Bob', age: 'unknown'}}); // "mocked" data response
console.error('%c /dancing/bats failed!', failure);console.log('/dancing/bats Does not exist');
You apply CSS rules in the string substitution with the %c
placeholder.
console.error('%c /dancing/bats failed!', failure);
Then place your CSS elements as a string argument and you can have CSS-styled logs. You can add more than one %c
into the string as well.
console.log('%cred %cblue %cwhite','color:red;','color:blue;', 'color: white;')
This will output the words ‘red’, ‘blue’ and ‘white’ in their respected colors.
There are quite a few CSS properties supported by the console. I would recommend experimenting to see what works and what doesn’t. Again, your results may vary depending on your browser.
Other available methods
Here are a few other available console
methods. Note that some items below have not had their APIs standardized, so there may be incompatibilities between the browsers. The examples were created with Firefox 51.0.1.
Assert()
Assert
takes two arguments — if the first argument evaluates to a falsy value, then it displays the second argument.
let isTrue = false;
console.assert(isTrue, 'This will display');
isTrue = true;
console.assert(isTrue, 'This will not');
If the assertion is false, it outputs to the console. It’s displayed as an error-level log as mentioned above, giving you both a red error message and a stack trace.
Dir()
The dir
method displays an interactive list of the object passed to it.
console.dir(document.body);

Ultimately, dir
only saves one or two clicks. If you need to inspect an object from an API response, then displaying it in this structured way can save you some time.
Table()
The table
method displays an array or object as a table.
console.table(['Javascript', 'PHP', 'Perl', 'C++']);

The array’s indices or object property names come under the left-hand index column. Then the values are displayed in the right-hand column.
const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table(superhero);

Note for Chrome users: This was brought to my attention by a co-worker but the above examples of the table
method don’t seem to work in Chrome. You can work around this issue by placing any items into an array of arrays or an array of objects:
console.table([['Javascript', 'PHP', 'Perl', 'C++']]);
const superhero = { firstname: 'Peter', lastname: 'Parker',}console.table([superhero]);
Group()
console.group()
is made up of at least a minimum of three console
calls, and is probably the method that requires the most typing to use. But it’s also one of the most useful (especially for developers using Redux Logger).
A somewhat basic call looks like this:
console.group();console.log('I will output');console.group();console.log('more indents')console.groupEnd();console.log('ohh look a bear');console.groupEnd();
This will output multiple levels and will display differently depending on your browser.
Firefox shows an indented list:

Chrome shows them in the style of an object:

Each call to console.group()
will start a new group, or create a new level if it’s called inside a group. Each time you call console.groupEnd()
it will end the current group or level and move back up one level.
I find the Chrome output style is easier to read since it looks more like a collapsible object.
You can pass group
a header argument that will be displayed over console.group
:
console.group('Header');
You can display the group as collapsed from the outset if you call console.groupCollapsed()
. Based on my experience, this seems to work only in Chrome.
Time()
The time
method, like the group
method above, comes in two parts.
A method to start the timer and a method to end it.
Once the timer has finished, it will output the total runtime in milliseconds.
To start the timer, you use console.time('id for timer')
and to end the timer you use console.timeEnd('id for timer')
. You can have up to 10,000 timers running simultaneously.
The output will look a bit like this timer: 0.57ms
It is very useful when you need to do a quick bit of benchmarking.
Conclusion
There we have it, a bit of a deeper look into the console object and some of the other methods that come with it. These methods are great tools to have available when you need to debug code.
There are a couple of methods that I have not talked about as their API is still changing. You can read more about them or the console in general on the MDN Web API page and its living spec page.
