console.log を使いこなす - JavaScript
console.log は JavaScript で最も使われるデバッグ手法です。単純に見えて、実は多彩な使い方ができます。効率的なデバッグのために、いくつかのテクニックを身につけておきましょう。
基本の出力
console.log('Hello, World!');
console.log(123);
console.log({ name: 'Alice', age: 30 });
console.log([1, 2, 3]);文字列、数値、オブジェクト、配列など、あらゆる値を出力できます。
複数の値をまとめて出力
カンマ区切りで複数の値を一度に出力できます。
const name = 'Alice';
const age = 30;
console.log('名前:', name, '年齢:', age);
// 名前: Alice 年齢: 30文字列連結よりも見やすく、型変換の心配もありません。
オブジェクト名付きで出力する
オブジェクトを出力するとき、何の変数かわかりにくいことがあります。オブジェクトのショートハンド記法を使うと便利です。
const user = { name: 'Alice', age: 30 };
const settings = { theme: 'dark', lang: 'ja' };
// 何がどれかわかりにくい
console.log(user, settings);
// 変数名がキーになって見やすい
console.log({ user, settings });
// { user: { name: 'Alice', age: 30 }, settings: { theme: 'dark', lang: 'ja' } }プレースホルダを使ったフォーマット
C 言語の printf のように、フォーマット指定子を使うことも可能です。
console.log('名前: %s, 年齢: %d', 'Alice', 30);
// 名前: Alice, 年齢: 30
console.log('オブジェクト: %o', { a: 1, b: 2 });
// オブジェクト: {a: 1, b: 2}| %s | 文字列 |
| %d / %i | 整数 |
| %f | 浮動小数点数 |
| %o | オブジェクト(展開可能) |
| %O | オブジェクト(展開不可) |
| %c | CSS スタイル |
CSS でスタイリング
%c を使うと、出力にスタイルを適用できます。
console.log(
'%c警告%c この操作は取り消せません',
'background: orange; color: white; padding: 2px 6px; border-radius: 3px;',
''
);ライブラリやフレームワークがロゴを表示するのに使っていることがあります。
テンプレートリテラルとの組み合わせ
ES6 のテンプレートリテラルを使うと、変数の埋め込みが簡単です。
const item = 'りんご';
const price = 150;
console.log(`${item}の価格は${price}円です`);
// りんごの価格は150円です条件付きログ出力
開発環境でのみログを出力したい場合は、条件分岐を使います。
const DEBUG = true;
function debugLog(...args) {
if (DEBUG) {
console.log('[DEBUG]', ...args);
}
}
debugLog('処理を開始します');本番環境では DEBUG を false にするか、ビルド時に削除するよう設定します。
ログにタイムスタンプを付ける
処理の実行タイミングを確認したいときは、タイムスタンプを付けると便利です。
function logWithTime(...args) {
const now = new Date().toISOString();
console.log(`[${now}]`, ...args);
}
logWithTime('処理開始');
// [2024-01-15T10:30:00.123Z] 処理開始JSON.stringify で整形出力
深くネストしたオブジェクトを見やすく出力するには JSON.stringify を使います。
const data = {
user: { name: 'Alice', profile: { age: 30, city: 'Tokyo' } },
items: [1, 2, 3]
};
console.log(JSON.stringify(data, null, 2));第 3 引数にインデント幅を指定すると、整形されて出力されます。