概要
JavaScriptとは
WebブラウザやNode.jsなどで動作する、世界で最も広く使われるスクリプト言語の一つ。DOM操作、通信、描画、ビルド/テスト/自動化まで幅広く活躍します。
- 実行環境:ブラウザ、Node.js、Deno、Bun
- モジュール:ESM(推奨) / CJS(Node互換)
- 主要分野:Webフロント、サーバサイド、ツール、ゲーム、データ可視化
このページの使い方
- 左の目次でジャンプ、右上でテーマ切替
- ⌘/Ctrl + F でも検索OK、上の検索バーは動的絞り込み
- コードは右上の Copy ボタンでクリップボードへ
- 下部の「プレイグラウンド」でコード実行
基礎
// 変数と基本型
let n = 42; // number
const s = "hello"; // string
let ok = true; // boolean
let arr = [1,2,3]; // array
let obj = { a: 1 }; // object
let u; // undefined
let z = null; // null
// 条件分岐
if (n > 0) {
console.log("positive");
} else if (n === 0) {
console.log("zero");
} else {
console.log("negative");
}
// ループ
for (const x of arr) {
console.log(x);
}
// 関数(アロー)
const add = (a, b) => a + b;
console.log(add(3, 5)); // 8
配列/オブジェクト操作
const users = [
{ id: 1, name: "A", score: 80 },
{ id: 2, name: "B", score: 92 },
];
// map/filter/reduce
const names = users.map(u => u.name);
const high = users.filter(u => u.score >= 90);
const total = users.reduce((acc,u) => acc + u.score, 0);
// 分割代入/スプレッド
const { id, ...rest } = users[0];
const more = [...users, { id: 3, name: "C", score: 70 }];
非同期(Promise/async)
const sleep = ms => new Promise(r => setTimeout(r, ms));
async function demo() {
console.log("start");
await sleep(500);
console.log("after 0.5s");
}
demo();
// fetch(エラーハンドリング例)
async function loadJSON(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(res.status + " " + res.statusText);
return res.json();
}
基本
// クラス
export class Counter {
#value = 0; // プライベートフィールド
inc(){ this.#value++; }
get value(){ return this.#value; }
}
// DOM & イベント
document.addEventListener('click', (e) => {
if (e.target.matches('[data-hello]')) {
console.log("Hello clicked!");
}
});
✅ ESMの読み込み(ブラウザ)サンプル
<script type="module">
import { Counter } from './counter.js';
const c = new Counter();
c.inc();
console.log(c.value);
</script>
最新情報
- モジュール/ESM:
type="module"でブラウザもネイティブ対応。 - Fetch/Streams:標準のネットワークAPI、ストリーム処理。
- Intl.*:日付/数値/相対時刻など国際化API。
- Web Components:
customElements/ Shadow DOM。 - Service Worker:オフライン/キャッシュ戦略。
- 型:JSDocで型補助 or TypeScript併用が実務定番。
応用
フォーム検証(Constraint Validation API)
const form = document.querySelector('#sampleForm');
form?.addEventListener('submit', (e) => {
if (!form.checkValidity()) {
e.preventDefault();
form.reportValidity();
}
});
ローカルストレージ
const KEY = "prefs";
const prefs = JSON.parse(localStorage.getItem(KEY) ?? "{}");
prefs.theme = "dark";
localStorage.setItem(KEY, JSON.stringify(prefs));
🎨 Canvasで簡単に描画
const cvs = document.querySelector('canvas');
const ctx = cvs.getContext('2d');
ctx.fillStyle = '#4f46e5';
ctx.fillRect(10, 10, 120, 60);
ctx.fillStyle = '#fff';
ctx.font = '20px system-ui';
ctx.fillText('JS Lab', 20, 45);
発展
- テスト:Vitest/Jest + Playwright でユニット〜E2E
- ビルド:Vite を軸にESM運用、CDNでUNPKG/SKYPACKも
- 性能:
PerformanceAPI、requestIdleCallback、Web Worker - アクセシビリティ:WAI-ARIA / セマンティックHTML徹底
// Web Worker の最小例(inline)
const worker = new Worker(URL.createObjectURL(new Blob([`
self.onmessage = (e) => {
// 重い計算の代わり
let sum = 0; for(let i=0;i<5e6;i++) sum += i;
self.postMessage(sum);
};
`], { type: 'text/javascript' })));
worker.onmessage = (e) => console.log('sum:', e.data);
worker.postMessage('go');