JavaScriptでできること一覧 - Web開発の可能性を初心者向けに解説

JavaScriptでできることを初心者向けに総合的に解説。Web開発、アプリ開発、ゲーム制作など、JavaScriptの幅広い可能性と具体例を紹介します。

Learning Next 運営
24 分で読めます

JavaScriptでできること一覧 - Web開発の可能性を初心者向けに解説

みなさん、JavaScriptって聞いたことはあるけど、実際に何ができるか知っていますか?

「プログラミングに興味があるけど、JavaScriptって何ができるの?」 「Web以外でも使えるって本当?」 こんな疑問を持っている方、きっと多いですよね。

実は、JavaScriptはとても幅広い分野で活躍できる言語なんです! この記事では、JavaScriptでできることを初心者向けに分かりやすく解説します。 きっと「こんなこともできるの?」と驚くはずですよ。

JavaScriptって何?基本を知ろう

世界で一番人気の言語

JavaScriptは、世界で最も広く使われているプログラミング言語の一つです。

簡単に言うと、Webページに動きをつけたり、いろいろなアプリを作ったりできる言語なんです。 元々はWebブラウザで動くために作られましたが、今では本当にたくさんの場所で使われています。

JavaScriptの魅力的な特徴

JavaScriptにはこんな魅力があります。

  • 学習しやすい: 文法がシンプルで覚えやすい
  • すぐに始められる: ブラウザがあれば今すぐ試せる
  • 何でも作れる: Webサイトからアプリまで幅広く対応
  • 情報が豊富: 困った時の情報がたくさん見つかる
  • 仲間が多い: 世界中に開発者がいて活発

これだけでも、JavaScriptを学ぶ価値があると思いませんか?

Webページを動かしてみよう

ページに動きを追加する

まずは基本中の基本、Webページに動きをつけることから始めましょう。

<!DOCTYPE html>
<html>
<head>
<title>JavaScriptでページ操作</title>
</head>
<body>
<h1 id="title">ようこそ</h1>
<button id="changeButton">タイトルを変更</button>
<button id="colorButton">色を変更</button>
<script>
// タイトルの変更
document.getElementById('changeButton').addEventListener('click', function() {
document.getElementById('title').textContent = 'JavaScriptが動いています!';
});
// 色の変更
document.getElementById('colorButton').addEventListener('click', function() {
const title = document.getElementById('title');
const colors = ['red', 'blue', 'green', 'purple', 'orange'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
title.style.color = randomColor;
});
</script>
</body>
</html>

このコードでは、ボタンをクリックするとタイトルの文字や色が変わります。 これだけでも、Webページがグッと面白くなりますよね。

リアルタイムな操作

ユーザーの操作にリアルタイムで反応するページも作れます。

// マウスの動きに追従する要素
document.addEventListener('mousemove', function(event) {
const follower = document.getElementById('mouse-follower');
if (follower) {
follower.style.left = event.clientX + 'px';
follower.style.top = event.clientY + 'px';
}
});
// キーボード入力のリアルタイム処理
document.getElementById('search-input').addEventListener('input', function(event) {
const query = event.target.value;
if (query.length > 2) {
performSearch(query);
}
});
function performSearch(query) {
console.log('検索中:', query);
// 実際の検索処理をここに書く
}

マウスカーソルに要素が付いてきたり、入力と同時に検索が始まったり。 こんな機能があると、サイトがとても使いやすくなります。

本格的なWebアプリを作ってみよう

シングルページアプリケーション

現代的なWebアプリは、ページをリロードせずに画面を切り替えることができます。

// シンプルなSPAルーター
class SimpleRouter {
constructor() {
this.routes = {};
this.currentRoute = '';
}
// ルートを登録
route(path, handler) {
this.routes[path] = handler;
}
// ページ遷移
navigate(path) {
if (this.routes[path]) {
this.currentRoute = path;
this.routes[path]();
// ブラウザの履歴を更新
window.history.pushState({}, '', path);
}
}
}
// 使用例
const router = new SimpleRouter();
router.route('/', () => {
document.getElementById('app').innerHTML = '<h1>ホームページ</h1>';
});
router.route('/about', () => {
document.getElementById('app').innerHTML = '<h1>会社概要</h1>';
});

このルーターを使えば、ページをリロードすることなく画面を切り替えられます。 まるでアプリのような動作ですね。

チャットアプリも作れる

WebSocketを使えば、リアルタイムで通信するアプリも作れます。

// リアルタイムチャットアプリ
class ChatApp {
constructor() {
this.socket = null;
this.username = '';
}
// WebSocket接続
connect(username) {
this.username = username;
this.socket = new WebSocket('ws://localhost:8080');
this.socket.onopen = () => {
console.log('チャットに接続しました');
};
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data);
this.displayMessage(message);
};
}
// メッセージ送信
sendMessage(content) {
const message = {
username: this.username,
content: content,
timestamp: new Date().toISOString()
};
this.socket.send(JSON.stringify(message));
}
// メッセージ表示
displayMessage(message) {
const chatContainer = document.getElementById('chat-messages');
const messageElement = document.createElement('div');
messageElement.innerHTML = `
<span class="username">${message.username}:</span>
<span class="content">${message.content}</span>
`;
chatContainer.appendChild(messageElement);
}
}

これで、LINEやSlackのようなチャットアプリの基本機能ができました。 リアルタイムで会話できるなんて、すごいですよね。

データを見やすくしてみよう

グラフやチャートを作る

数字の羅列では分からないデータも、グラフにすると一目瞭然です。

// 簡単なチャート作成
class SimpleChart {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
}
// 棒グラフの描画
drawBarChart(data, labels) {
const width = this.canvas.width;
const height = this.canvas.height;
const barWidth = width / data.length;
const maxValue = Math.max(...data);
// 背景をクリア
this.ctx.clearRect(0, 0, width, height);
// 棒グラフを描画
data.forEach((value, index) => {
const barHeight = (value / maxValue) * height * 0.8;
const x = index * barWidth;
const y = height - barHeight;
// 棒を描画
this.ctx.fillStyle = `hsl(${index * 60}, 70%, 50%)`;
this.ctx.fillRect(x + 10, y, barWidth - 20, barHeight);
// ラベルを描画
this.ctx.fillStyle = 'black';
this.ctx.font = '12px Arial';
this.ctx.fillText(labels[index], x + barWidth/2 - 10, height - 5);
});
}
}
// 使用例
const chart = new SimpleChart('chart-canvas');
const salesData = [120, 190, 300, 500, 200, 300];
const monthLabels = ['1月', '2月', '3月', '4月', '5月', '6月'];
chart.drawBarChart(salesData, monthLabels);

売上データなどを視覚的に表示することで、傾向が一目で分かるようになります。

ゲームを作ってみよう

ブラウザで遊べるゲーム

HTML5 Canvasを使えば、ブラウザで動くゲームも作れます。

// シンプルなブロック崩しゲーム
class BreakoutGame {
constructor(canvasId) {
this.canvas = document.getElementById(canvasId);
this.ctx = this.canvas.getContext('2d');
// ゲーム要素
this.ball = { x: 200, y: 300, dx: 3, dy: -3, radius: 8 };
this.paddle = { x: 150, y: 350, width: 100, height: 10 };
this.score = 0;
this.setupControls();
}
// キーボード操作を設定
setupControls() {
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft' && this.paddle.x > 0) {
this.paddle.x -= 8;
}
if (e.key === 'ArrowRight' && this.paddle.x < this.canvas.width - this.paddle.width) {
this.paddle.x += 8;
}
});
}
// ゲームの更新
update() {
// ボールの移動
this.ball.x += this.ball.dx;
this.ball.y += this.ball.dy;
// 壁との衝突判定
if (this.ball.x <= 0 || this.ball.x >= this.canvas.width) {
this.ball.dx = -this.ball.dx;
}
if (this.ball.y <= 0) {
this.ball.dy = -this.ball.dy;
}
// パドルとの衝突判定
if (this.ball.y >= this.paddle.y - this.ball.radius &&
this.ball.x >= this.paddle.x &&
this.ball.x <= this.paddle.x + this.paddle.width) {
this.ball.dy = -this.ball.dy;
}
}
// 描画
draw() {
// 画面をクリア
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// ボールを描画
this.ctx.beginPath();
this.ctx.arc(this.ball.x, this.ball.y, this.ball.radius, 0, Math.PI * 2);
this.ctx.fillStyle = 'red';
this.ctx.fill();
// パドルを描画
this.ctx.fillStyle = 'blue';
this.ctx.fillRect(this.paddle.x, this.paddle.y, this.paddle.width, this.paddle.height);
}
}

ブロック崩しやパズルゲームなど、懐かしいゲームも簡単に作れます。

サーバーも作れちゃう

Node.jsでWebサーバー

JavaScriptはサーバーサイドでも動きます。 Node.jsを使えば、Webサーバーも作れるんです。

// Express.jsを使ったWebサーバー
const express = require('express');
const app = express();
const port = 3000;
// 静的ファイルの提供
app.use(express.static('public'));
app.use(express.json());
// ルートの定義
app.get('/', (req, res) => {
res.send(`
<h1>Node.js Webサーバー</h1>
<p>JavaScriptでサーバーサイド開発!</p>
`);
});
// APIエンドポイント
const users = [
{ id: 1, name: '田中太郎', email: 'tanaka@example.com' },
{ id: 2, name: '佐藤花子', email: 'sato@example.com' }
];
app.get('/api/users', (req, res) => {
res.json(users);
});
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(newUser);
res.json(newUser);
});
// サーバー起動
app.listen(port, () => {
console.log(`サーバーがポート${port}で起動しました`);
});

この短いコードで、立派なWebサーバーができちゃいます。 APIも作れるので、アプリのバックエンドも任せられますね。

モバイルアプリも作れる

PWA(プログレッシブWebアプリ)

Webアプリをスマホアプリのように動作させることもできます。

// Service Worker の登録
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker登録成功');
})
.catch(error => {
console.log('Service Worker登録失敗');
});
}
// プッシュ通知の設定
class NotificationManager {
async requestPermission() {
if ('Notification' in window) {
const permission = await Notification.requestPermission();
return permission === 'granted';
}
return false;
}
async showNotification(title, options) {
if (await this.requestPermission()) {
new Notification(title, options);
}
}
}
// オフライン対応
window.addEventListener('online', () => {
console.log('オンラインに戻りました');
});
window.addEventListener('offline', () => {
console.log('オフラインモードです');
});

PWAを使えば、Webアプリをスマホにインストールして、ネイティブアプリのように使えます。

デスクトップアプリまで

Electronでデスクトップアプリ

なんと、デスクトップアプリまで作れるんです。

// Electronを使ったデスクトップアプリ
const { app, BrowserWindow } = require('electron');
class DesktopApp {
constructor() {
this.mainWindow = null;
this.setupApp();
}
setupApp() {
app.whenReady().then(() => {
this.createMainWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
}
createMainWindow() {
this.mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true
}
});
// HTMLファイルを読み込み
this.mainWindow.loadFile('index.html');
}
}
// アプリケーション起動
new DesktopApp();

Visual Studio CodeやSlackなど、有名なアプリもElectronで作られているんですよ。

人工知能まで動かせる

ブラウザで機械学習

TensorFlow.jsを使えば、ブラウザ上で機械学習も実行できます。

// 画像分類AI
class ImageClassifier {
constructor() {
this.model = null;
}
async loadModel() {
// 事前訓練済みモデルを読み込み
this.model = await tf.loadLayersModel('/models/my-model.json');
console.log('AIモデルが読み込まれました');
}
async classifyImage(imageElement) {
if (!this.model) {
await this.loadModel();
}
// 画像を前処理
const tensor = tf.browser.fromPixels(imageElement)
.resizeNearestNeighbor([224, 224])
.toFloat()
.div(tf.scalar(255))
.expandDims();
// AI予測実行
const predictions = await this.model.predict(tensor).data();
return this.processPredictions(predictions);
}
processPredictions(predictions) {
const labels = ['犬', '猫', '鳥', '魚'];
const results = [];
for (let i = 0; i < predictions.length; i++) {
results.push({
label: labels[i],
confidence: predictions[i]
});
}
return results.sort((a, b) => b.confidence - a.confidence);
}
}

画像を投げると「これは犬です(信頼度90%)」なんて判定してくれるAIが作れちゃいます。

まとめ:JavaScriptの無限の可能性

JavaScriptでできることをたくさん紹介しましたが、いかがでしたか?

JavaScriptの素晴らしいところ

  • Webページの動的な操作: ボタンクリックで画面が変わる
  • 本格的なWebアプリ: チャットアプリやSPAが作れる
  • データの可視化: グラフやチャートで情報を分かりやすく
  • ゲーム開発: ブラウザで遊べるゲームが作れる
  • サーバーサイド開発: WebサーバーやAPIが作れる
  • モバイルアプリ: PWAでスマホアプリのような体験
  • デスクトップアプリ: パソコンで動くアプリが作れる
  • AI・機械学習: ブラウザ上でAIが動かせる

一つの言語でこれだけのことができるなんて、本当にすごいですよね。

これからJavaScriptを学ぶあなたへ

JavaScriptを学べば、Web開発からアプリ開発、さらにはAIまで、本当に幅広い分野で活躍できます。 どの分野に興味があっても、JavaScriptが活躍する場面がきっと見つかるはずです。

まずは簡単なWebページの操作から始めて、だんだんと難しいことにも挑戦してみてください。 きっと「プログラミングって楽しい!」と感じられるはずですよ。

ぜひ今日から、JavaScriptの世界に飛び込んでみませんか?

関連記事