LoginSignup
1
1

consoleオブジェクトの種類

Posted at

はじめに

Javascriptを使ったことがある人はおなじみのconsoleオブジェクトがありますね!
よく使うものとしては、↓があると思います。

index.js
console.log()
console.error()

実は、これ以外にもたくさん種類があり、使い方によっては開発効率があがることも...?
それらを紹介していきます!

console.assert(条件, 出力)

条件の部分にif文で使うような条件を入れることができ、条件がfalseの場合に出力をします。

example.js
const number = 0;
console.assert(number === 1, "numberは1ではありません。");

//出力:numberは1ではありません。

console.clear()

単純に、これまでのコンソールをすべて綺麗さっぱり消してしまいます。

console.count()、 countReset()

コード内で何度実行したかカウントし、出力されます。

example.js
console.count("実行した回数");
//出力:実行した回数: 1

console.count("実行した回数");
//出力:実行した回数: 2


console.countReset("実行した回数");
console.count("実行した回数");
//出力:実行した回数: 1

console.debug()

デバッグ目的で使用するconsole.log()です。

example.js
console.debug("これはデバッグログです。");
//出力:これはデバッグログです。

console.dir()

オブジェクトや配列など、複雑なネスト構造を含んでいるデータを視覚的に理解しやすい形式で出力されます。

example.js
const obj = {
    Name: "たこ",
    Age: 15,
    FavoriteColor: ["yello", "orange", "blue"],
    Address: {
        Country: "Japan",
        City: "Tokyo"
    }
}
console.dir(obj);


/*
出力:

Object
  Address: Object
    City: "Tokyo"
    Country: "Japan"
  Age: 15
  FavoriteColor: Array(3)
    0: "yello"
    1: "orange"
    2: "blue"
    length: 3
  Name: "たこ"
*/

console.dirxml()

console.dir()と同じ用途ですが、XMLとして出力されるようになります。

example.js
const obj = {
    Name: "たこ",
    Age: 15,
    FavoriteColor: ["yello", "orange", "blue"],
    Address: {
        Country: "Japan",
        City: "Tokyo"
    }
}
console.dirxml(obj);


/*
出力:

<object>
  <Address>
    <City>Tokyo</City>
    <Country>Japan</Country>
  </Address>
  <Age>15</Age>
  <FavoriteColor>
    <item>yello</item>
    <item>orange</item>
    <item>blue</item>
  </FavoriteColor>
  <Name>たこ</Name>
</object>
*/

console.error()

エラーハンドリングなどで取得したエラーを出力するために使います。
console.error()を用いて出力されたものは、赤色のテキストで表示されるようになります。

example.js
MyFunction()
    .catch((e) => {
        console.error(e);
    });


/*
出力例:

ReferenceError: abc is not defined
    at MyFunction (/workspace/Main.js:2:17)
    at Object.<anonymous> (/workspace/Main.js:5:1)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47
*/

※MyFunctionの定義は割愛しています。

console.group()、 groupCollapsed()、 groupEnd()

たくさんの情報をログに出すときに、グループ化することで見やすくすることができます。
イメージ的には、ログに階層構造をつけるような感じです。

example.js
console.group('グループ1');
console.log('グループ1の要素');
console.groupCollapsed('グループ2');
console.log('グループ2の要素');
console.log('グループ2の要素');
console.groupEnd(); // グループ2をここまでにする
console.log('グループ1の要素');
console.groupEnd(); //グループ1をここまででにする(グループの終了)


/*
出力:

グループ1
  グループ1の要素
  グループ2
    グループ2の要素
    グループ2の要素
  グループ1の要素
*/

console.info()

情報を提示するなどの目的で使用するconsole.log()です。

example.js
console.info("これは情報メッセージです、");

//出力:これは情報メッセージです。

console.profile()、 profileEnd()

特定の処理のプロファイリングをするのに使用します。
結果はコンソールに直接表示されず、devツールのパフォーマンスタブに表示されることが多いです。

example.js
console.profile("プロファイリング名");
//なんらかの処理
console.profileEnd("プロファイリング名");

※コンソール出力ではないため出力は省略しています。

console.table()

配列の中に含まれた複数のオブジェクトを、テーブルにして出力します。
SQLみたいなものです。

example.js
const data = [
  { id: '357938475', name: "tacopic002" },
  { id: '725372523', name: "tacopic003" },
  { id: '420598487', name: "tacopic004" }
];
console.table(data);


/*
出力:

┌─────────┬─────────────┬──────────────┐
│ (index) │     id      │     name     │
├─────────┼─────────────┼──────────────┤
│    0    │ '357938475' │ 'tacopic002' │
│    1    │ '725372523' │ 'tacopic003' │
│    2    │ '420598487' │ 'tacopic004' │
└─────────┴─────────────┴──────────────┘
*/

console.time()、 timeEnd()、 timeLog()

処理にかかっている時間を単純に計測し、ログに出力します。
console.timeLog()は計測途中での処理時間を出力します。

example.js
console.time('myTimer');
//何らかの処理
console.timeLog('myTimer');
//何らかの処理
console.timeEnd('myTimer');


/*
出力例:

myTimer: 2.24ms
myTimer: 5.636ms
*/

console.timeStamp()

処理を開始したときや、終了したときのタイムライン上での地点をマークします。
ログとして出力されず、devツールのパフォーマンスタブで表示されることが多いです。

example.js
console.timeStamp('処理を開始');
//なんらかの処理
console.timeStamp('処理が終了');

※コンソール出力ではないため出力は省略しています。

console.trace()

エラーなどが発生したときに、どこから呼び出されているかなどを確認できるログです。
どこの関数でエラーが発生しているのかなどの特定がしやすくなります。

example.js
function foo() {
    bar();
}
function bar() {
    console.trace();
}
foo();

/*
出力:

Trace
    at bar (/workspace/Main.js:5:13)
    at foo (/workspace/Main.js:2:5)
    at Object.<anonymous> (/workspace/Main.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47
*/

console.warn()

実際にエラーは発生していないものの、今後廃止されるメソッドを使用していたり、非推奨のメソッドや関数を使用していた場合に黄色のテキストで出力します。
(テキストのカラーはブラウザによって差異があります。)

example.js
const Number = "String";
if (isNaN(Number)) return console.warn("予期しない型が入力されています。");

//出力:予期しない型が入力されています。

これでほとんどのconsoleを紹介しました!
以外に使いやすいものが見つかれば嬉しいです!

consoleの種類によっては、出力例として実行したものもあります。(error()、 trace()とか)
これらは、Paiza.ioさんを利用して実行しました。

参考:https://developer.mozilla.org/ja/docs/Web/API/console

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1