JavaScriptで電卓を作ろう!初心者向け実践チュートリアル
JavaScriptで電卓アプリを作る方法を初心者向けに完全解説。HTML、CSS、JavaScriptを使って実際に動く電卓を段階的に作成する実践チュートリアルです。
JavaScriptで電卓を作ろう!初心者向け実践チュートリアル
JavaScript学習中の皆さん、こんな想いを抱いたことはありませんか?
「勉強した知識を使って、実際に動くものを作ってみたい!」 「でも何から始めればいいか分からない...」
そんな方にぴったりなのが電卓アプリです。 電卓なら誰でも使い方を知っているので、作る目標が明確ですよね。
この記事では、JavaScriptで電卓アプリを作る方法を初心者向けに完全解説します。 HTML、CSS、JavaScriptを使って、実際に動く電卓を段階的に作成していきましょう。
変数、関数、イベント処理、DOM操作など、JavaScriptの重要な概念を楽しく身につけることができますよ。
今回作る電卓の完成イメージ
どんな電卓を作るの?
まずは、作成する電卓の完成イメージを確認しましょう。
今回作る電卓の機能はこちらです。
- 四則演算(+、-、×、÷)
- 小数点計算
- クリアボタン(C)
- イコールボタン(=)
- 連続計算機能
見た目もスマートフォンの電卓アプリのような、使いやすいデザインにします。 ボタンを押すと色が変わったり、ホバー効果もつけますよ。
実際に手を動かしながら学習することで、JavaScriptの実践的なスキルが身につきます。
学習できるポイント
このチュートリアルを通して、以下のスキルが習得できます。
- HTML: 構造化されたマークアップの書き方
- CSS: Grid レイアウトとスタイリングの実践
- JavaScript: クラス設計とDOM操作の基礎
一つひとつ丁寧に説明していくので、初心者の方でも安心してついてきてくださいね。
プロジェクトの準備をしよう
ファイル構成を確認
最初に、プロジェクトのファイル構成を決めましょう。
今回は以下のような構成で進めます。
calculator/
├── index.html
├── style.css
└── script.js
シンプルな構成ですが、実際の開発でもよく使われるパターンです。 役割ごとにファイルを分けることで、コードが整理されて読みやすくなります。
HTMLファイルを作成しよう
まずは電卓の骨組みとなるHTMLファイルを作成します。
<!DOCTYPE html><html lang="ja"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript電卓</title> <link rel="stylesheet" href="style.css"></head><body> <div class="calculator"> <div class="display"> <div class="current-operand" id="currentOperand">0</div> <div class="previous-operand" id="previousOperand"></div> </div> <div class="buttons"> <button class="btn clear" onclick="calculator.clear()">C</button> <button class="btn operation" onclick="calculator.chooseOperation('÷')">÷</button> <button class="btn operation" onclick="calculator.chooseOperation('×')">×</button> <button class="btn delete" onclick="calculator.delete()">←</button> <button class="btn number" onclick="calculator.appendNumber('7')">7</button> <button class="btn number" onclick="calculator.appendNumber('8')">8</button> <button class="btn number" onclick="calculator.appendNumber('9')">9</button> <button class="btn operation" onclick="calculator.chooseOperation('-')">-</button> <button class="btn number" onclick="calculator.appendNumber('4')">4</button> <button class="btn number" onclick="calculator.appendNumber('5')">5</button> <button class="btn number" onclick="calculator.appendNumber('6')">6</button> <button class="btn operation" onclick="calculator.chooseOperation('+')">+</button> <button class="btn number" onclick="calculator.appendNumber('1')">1</button> <button class="btn number" onclick="calculator.appendNumber('2')">2</button> <button class="btn number" onclick="calculator.appendNumber('3')">3</button> <button class="btn equals" onclick="calculator.compute()">=</button> <button class="btn number zero" onclick="calculator.appendNumber('0')">0</button> <button class="btn number" onclick="calculator.appendNumber('.')">.</button> </div> </div> <script src="script.js"></script></body></html>
このHTMLコードを詳しく見てみましょう。
<div class="calculator">
で電卓全体を囲んでいます。
<div class="display">
は計算結果を表示する画面部分です。
<div class="buttons">
の中に、電卓のボタンをすべて配置しています。
各ボタンにはonclick
属性で、クリック時に実行する関数を指定していますね。
例えばonclick="calculator.appendNumber('7')"
は、「7」ボタンがクリックされた時に数字を追加する処理です。
CSSでスタイリングしよう
基本的なスタイルを設定
次に、電卓を美しく見せるためのCSSを書いていきます。
* { margin: 0; padding: 0; box-sizing: border-box;}
body { font-family: 'Arial', sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px;}
.calculator { background: #2c3e50; border-radius: 20px; padding: 20px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3); max-width: 320px; width: 100%;}
まずは全体的なスタイルを設定しています。
body
では、美しいグラデーション背景を設定して、電卓を画面中央に配置しています。
display: flex
を使うことで、簡単に中央配置ができますよ。
.calculator
クラスでは、電卓本体のスタイルを定義しています。
border-radius
で角を丸くして、box-shadow
で影をつけることで立体感を演出していますね。
ディスプレイ部分のスタイル
続いて、計算結果を表示する画面部分のスタイルです。
.display { background: #34495e; border-radius: 10px; padding: 20px; margin-bottom: 20px; text-align: right; min-height: 80px; display: flex; flex-direction: column; justify-content: center;}
.previous-operand { color: #bdc3c7; font-size: 18px; margin-bottom: 5px; min-height: 20px;}
.current-operand { color: white; font-size: 32px; font-weight: bold; word-wrap: break-word; word-break: break-all;}
ディスプレイは2段構成になっています。
previous-operand
は前の計算式を表示する部分で、グレーの文字で控えめに表示します。
current-operand
は現在の数値を表示する部分で、白色の大きな文字で目立たせています。
word-wrap
とword-break
で、長い数字が画面からはみ出さないようにしていますね。
ボタンのスタイル
最後に、ボタンのスタイルを設定しましょう。
.buttons { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px;}
.btn { height: 60px; border: none; border-radius: 10px; font-size: 20px; font-weight: bold; cursor: pointer; transition: all 0.2s ease; outline: none;}
.btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);}
.btn:active { transform: translateY(0);}
display: grid
を使って、ボタンを4列のグリッドレイアウトで配置しています。
gap: 15px
でボタン間のスペースを調整していますね。
:hover
と:active
で、ボタンにインタラクティブな動きを追加しています。
マウスを乗せると少し浮き上がり、クリックすると元に戻る動きです。
ボタンの種類別スタイル
ボタンの種類ごとに色分けして、使いやすくしましょう。
.btn.number { background: #3498db; color: white;}
.btn.number:hover { background: #2980b9;}
.btn.operation { background: #e67e22; color: white;}
.btn.operation:hover { background: #d35400;}
.btn.equals { background: #27ae60; color: white; grid-row: span 2;}
.btn.equals:hover { background: #229954;}
.btn.clear { background: #e74c3c; color: white;}
.btn.clear:hover { background: #c0392b;}
.btn.zero { grid-column: span 2;}
数字ボタンは青色、演算子ボタンはオレンジ色、という具合に色分けしています。 これにより、どのボタンがどんな役割なのか一目で分かりますね。
grid-row: span 2
で「=」ボタンを縦に2つ分の高さにしています。
grid-column: span 2
で「0」ボタンを横に2つ分の幅にしています。
JavaScript実装の基本編
電卓クラスの設計思想
いよいよJavaScriptの実装に入ります。 今回はクラスを使って電卓を作成しますよ。
なぜクラスを使うのかというと、電卓の機能をまとめて管理しやすくなるからです。
class Calculator { constructor(previousOperandElement, currentOperandElement) { this.previousOperandElement = previousOperandElement; this.currentOperandElement = currentOperandElement; this.clear(); }}
constructor
は、クラスのインスタンスが作成される時に自動で実行される特別な関数です。
ここで電卓の初期設定を行っています。
引数で受け取った2つの要素は、計算結果を表示するHTML要素ですね。
最後にthis.clear()
を呼んで、電卓を初期状態にリセットしています。
基本的な機能を実装しよう
まずは電卓の基本的な機能から実装していきます。
class Calculator { constructor(previousOperandElement, currentOperandElement) { this.previousOperandElement = previousOperandElement; this.currentOperandElement = currentOperandElement; this.clear(); } clear() { this.currentOperand = ''; this.previousOperand = ''; this.operation = undefined; this.updateDisplay(); } delete() { this.currentOperand = this.currentOperand.toString().slice(0, -1); if (this.currentOperand === '') { this.currentOperand = '0'; } this.updateDisplay(); } updateDisplay() { this.currentOperandElement.innerText = this.getDisplayNumber(this.currentOperand); if (this.operation != null) { this.previousOperandElement.innerText = `${this.getDisplayNumber(this.previousOperand)} ${this.operation}`; } else { this.previousOperandElement.innerText = ''; } }}
clear()
メソッドは、電卓の状態をすべてリセットします。
現在の数値、前の数値、演算子をすべて空にして、画面表示も更新しています。
delete()
メソッドは、入力した数字を1文字ずつ削除する機能です。
slice(0, -1)
で最後の1文字を削除して、もし空になったら「0」を表示します。
updateDisplay()
メソッドは、画面の表示を更新する重要な機能です。
現在の数値と、前の計算式を適切に表示しています。
数字入力の処理
次に、数字ボタンを押したときの処理を作りましょう。
appendNumber(number) { // 小数点の重複をチェック if (number === '.' && this.currentOperand.includes('.')) return; // 最初が0の場合の処理 if (this.currentOperand === '0') { if (number === '.') { this.currentOperand = '0.'; } else { this.currentOperand = number; } } else { this.currentOperand = this.currentOperand.toString() + number.toString(); } this.updateDisplay();}
appendNumber()
メソッドは、数字や小数点を入力する処理です。
最初のif
文で、小数点が重複しないようにチェックしています。
すでに小数点が含まれている場合は、処理を終了します。
次の部分では、現在の表示が「0」の時の特別な処理をしています。 小数点が押された場合は「0.」にして、数字が押された場合は「0」を置き換えています。
最後にupdateDisplay()
を呼んで、画面表示を更新していますね。
演算子の処理
演算子ボタンが押された時の処理も作りましょう。
chooseOperation(operation) { if (this.currentOperand === '') return; if (this.previousOperand !== '') { this.compute(); } this.operation = operation; this.previousOperand = this.currentOperand; this.currentOperand = ''; this.updateDisplay();}
chooseOperation()
メソッドは、+、-、×、÷などの演算子を選択する処理です。
最初のif
文で、現在の数値が空の場合は何もしないようにしています。
次の部分が重要で、すでに前の数値がある場合は先に計算を実行します。 これにより「2 + 3 + 4」のような連続計算ができるんです。
最後に、選択された演算子を保存して、現在の数値を前の数値に移動しています。
計算処理の実装
メインの計算ロジック
いよいよ電卓の心臓部、計算処理を実装しましょう。
compute() { let computation; const prev = parseFloat(this.previousOperand); const current = parseFloat(this.currentOperand); if (isNaN(prev) || isNaN(current)) return; switch (this.operation) { case '+': computation = prev + current; break; case '-': computation = prev - current; break; case '×': computation = prev * current; break; case '÷': if (current === 0) { alert('0で割ることはできません'); return; } computation = prev / current; break; default: return; } this.currentOperand = computation; this.operation = undefined; this.previousOperand = ''; this.updateDisplay();}
compute()
メソッドは、実際の計算を行う重要な機能です。
最初にparseFloat()
で文字列を数値に変換しています。
isNaN()
で、正しい数値かどうかをチェックしていますね。
switch
文で演算子ごとに処理を分けています。
足し算は+
、引き算は-
、という具合に分かりやすく書いています。
0で割ろうとした時は、エラーメッセージを表示して処理を停止します。 実際の電卓でも同じような動作をしますよね。
計算が完了したら、結果を現在の数値に設定して、演算子と前の数値をクリアしています。
表示フォーマットの改善
数字の表示をもっと見やすくしてみましょう。
getDisplayNumber(number) { if (number === '') return '0'; const stringNumber = number.toString(); const integerDigits = parseFloat(stringNumber.split('.')[0]); const decimalDigits = stringNumber.split('.')[1]; let integerDisplay; if (isNaN(integerDigits)) { integerDisplay = ''; } else { integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 }); } if (decimalDigits != null) { return `${integerDisplay}.${decimalDigits}`; } else { return integerDisplay; }}
getDisplayNumber()
メソッドは、数字を見やすい形式で表示するためのものです。
まず、空の場合は「0」を返すようにしています。
次に、数字を整数部分と小数部分に分けています。
split('.')
で小数点で分割して、それぞれを取得していますね。
toLocaleString()
を使うことで、大きな数字にカンマ区切りを入れることができます。
例えば「1000」が「1,000」と表示されるようになります。
最後に、小数部分がある場合は結合して返しています。
電卓インスタンスの作成
最後に、作成したクラスのインスタンスを作成しましょう。
// 電卓インスタンスの作成const previousOperandElement = document.getElementById('previousOperand');const currentOperandElement = document.getElementById('currentOperand');
const calculator = new Calculator(previousOperandElement, currentOperandElement);
HTMLで指定したIDの要素を取得して、電卓のインスタンスを作成しています。
new Calculator()
で新しい電卓オブジェクトが作られて、変数calculator
に格納されます。
これで基本的な電卓が完成です! ブラウザで開いて、実際に計算してみてくださいね。
高機能版の電卓を作ろう
履歴機能を追加
基本的な電卓ができたので、もっと便利な機能を追加してみましょう。
まずは計算履歴を保存する機能です。
class AdvancedCalculator extends Calculator { constructor(previousOperandElement, currentOperandElement) { super(previousOperandElement, currentOperandElement); this.history = []; this.memory = 0; } addToHistory(calculation) { this.history.push({ calculation: calculation, result: this.currentOperand, timestamp: new Date().toLocaleString() }); // 履歴は最大20件まで if (this.history.length > 20) { this.history.shift(); } this.updateHistoryDisplay(); }}
AdvancedCalculator
クラスは、基本のCalculator
クラスを拡張したものです。
extends
キーワードを使って、既存の機能を引き継いでいます。
addToHistory()
メソッドで、計算式と結果を履歴に保存しています。
計算式、結果、実行時刻をオブジェクトとして記録していますね。
履歴が20件を超えた場合は、古いものから削除して容量を節約しています。
メモリ機能の実装
電卓でよく使われるメモリ機能も追加しましょう。
memoryClear() { this.memory = 0; this.updateMemoryDisplay();}
memoryRecall() { this.currentOperand = this.memory.toString(); this.updateDisplay();}
memoryAdd() { if (this.currentOperand !== '') { this.memory += parseFloat(this.currentOperand); this.updateMemoryDisplay(); }}
memorySubtract() { if (this.currentOperand !== '') { this.memory -= parseFloat(this.currentOperand); this.updateMemoryDisplay(); }}
メモリ機能は4つのメソッドで構成されています。
memoryClear()
はメモリをクリア、memoryRecall()
はメモリの値を呼び出します。
memoryAdd()
はメモリに加算、memorySubtract()
はメモリから減算する機能です。
実際の電卓と同じような操作感で使えるようになっていますね。
科学計算機能
平方根や二乗などの科学計算機能も追加してみましょう。
squareRoot() { if (this.currentOperand === '') return; const number = parseFloat(this.currentOperand); if (number < 0) { alert('負の数の平方根は計算できません'); return; } const result = Math.sqrt(number); this.addToHistory(`√${number}`); this.currentOperand = result; this.updateDisplay();}
square() { if (this.currentOperand === '') return; const number = parseFloat(this.currentOperand); const result = number * number; this.addToHistory(`${number}²`); this.currentOperand = result; this.updateDisplay();}
percentage() { if (this.currentOperand === '') return; const number = parseFloat(this.currentOperand); const result = number / 100; this.addToHistory(`${number}%`); this.currentOperand = result; this.updateDisplay();}
squareRoot()
メソッドは平方根を計算します。
負の数の場合はエラーメッセージを表示して、計算を中止していますね。
square()
メソッドは二乗計算、percentage()
メソッドはパーセント計算です。
どの機能も計算履歴に記録されるようになっています。
Math.sqrt()
はJavaScriptの標準関数で、平方根を計算してくれます。
エラーハンドリングと入力検証
安全な電卓を作る
実用的な電卓にするために、エラーハンドリングを強化しましょう。
class ValidatedCalculator extends AdvancedCalculator { constructor(previousOperandElement, currentOperandElement) { super(previousOperandElement, currentOperandElement); this.maxDigits = 15; // 最大桁数 } appendNumber(number) { // 最大桁数チェック if (this.currentOperand.toString().replace('.', '').length >= this.maxDigits) { this.showError('最大桁数を超えています'); return; } // 先頭の0の処理 if (this.currentOperand === '0' && number !== '.') { this.currentOperand = ''; } super.appendNumber(number); }}
ValidatedCalculator
クラスは、入力検証機能を追加したバージョンです。
最大桁数を15桁に制限して、それを超える入力は受け付けないようにしています。 これにより、表示が崩れたり計算エラーが起きることを防げます。
エラーメッセージの表示
ユーザーに分かりやすいエラーメッセージを表示する機能も作りましょう。
showError(message) { const errorElement = document.getElementById('errorMessage'); if (errorElement) { errorElement.textContent = message; errorElement.style.display = 'block'; // 3秒後にエラーメッセージを非表示 setTimeout(() => { errorElement.style.display = 'none'; }, 3000); } else { alert(message); }}
validateResult(result) { if (typeof result !== 'number') { throw new Error('計算結果が数値ではありません'); } if (!isFinite(result)) { throw new Error('計算結果が無限大または非数値です'); } if (Math.abs(result) > Number.MAX_SAFE_INTEGER) { throw new Error('計算結果が安全な整数の範囲を超えています'); } return true;}
showError()
メソッドは、エラーメッセージを3秒間表示して自動で消す機能です。
専用のHTML要素がない場合は、alert()
でメッセージを表示します。
validateResult()
メソッドは、計算結果が正常な数値かどうかをチェックします。
無限大や非数値、範囲外の値をきちんと検出して、エラーを投げています。
入力値のサニタイズ
不正な入力を防ぐためのサニタイズ機能も追加しましょう。
sanitizeInput(input) { // 不正な文字を除去 return input.replace(/[^0-9+\-×÷=.]/g, '');}
compute() { if (this.currentOperand === '' || this.previousOperand === '') { this.showError('計算に必要な数値が不足しています'); return; } const prev = parseFloat(this.previousOperand); const current = parseFloat(this.currentOperand); // オーバーフローチェック if (Math.abs(prev) > Number.MAX_SAFE_INTEGER || Math.abs(current) > Number.MAX_SAFE_INTEGER) { this.showError('数値が大きすぎます'); return; } // 0除算チェック if (this.operation === '÷' && current === 0) { this.showError('0で割ることはできません'); return; } super.compute(); // 結果の検証 const result = parseFloat(this.currentOperand); if (!isFinite(result)) { this.showError('計算結果が範囲を超えました'); this.clear(); return; }}
sanitizeInput()
メソッドは、正規表現を使って不正な文字を除去します。
数字と演算子以外の文字は、すべて削除されるようになっています。
改良されたcompute()
メソッドでは、様々なエラーパターンをチェックしています。
オーバーフロー、0除算、結果の検証など、実用的な電卓に必要な機能です。
キーボード対応とアクセシビリティ
キーボードで操作できる電卓
マウスだけでなく、キーボードでも操作できるようにしましょう。
handleKeyboard(event) { const key = event.key; // 数字キー if ((key >= '0' && key <= '9') || key === '.') { this.appendNumber(key); } // 演算子キー switch (key) { case '+': this.chooseOperation('+'); break; case '-': this.chooseOperation('-'); break; case '*': this.chooseOperation('×'); break; case '/': event.preventDefault(); // ブラウザの検索機能を無効化 this.chooseOperation('÷'); break; case 'Enter': case '=': this.compute(); break; case 'Escape': case 'c': case 'C': this.clear(); break; case 'Backspace': this.delete(); break; }}
handleKeyboard()
メソッドは、キーボードの入力を電卓の操作に変換します。
数字キーと小数点は直接数字入力に使えます。 演算子キーは、キーボードの記号と電卓の演算子を対応付けています。
EnterキーとEscapeキーは、よく使われるショートカットとして設定していますね。
event.preventDefault()
で、ブラウザのデフォルト動作を無効化しています。
アクセシビリティの改善
視覚障害者の方でも使えるように、アクセシビリティを改善しましょう。
<!-- アクセシビリティを考慮したHTML --><div class="calculator" role="application" aria-label="電卓"> <div class="display" aria-live="polite" aria-label="計算結果表示"> <div class="previous-operand" id="previousOperand" aria-label="前の計算"></div> <div class="current-operand" id="currentOperand" aria-label="現在の数値">0</div> </div> <div class="buttons" role="grid"> <button class="btn clear" onclick="calculator.clear()" aria-label="全てクリア" tabindex="0">C</button> <button class="btn number" onclick="calculator.appendNumber('1')" aria-label="数字の1" tabindex="0">1</button> </div></div>
role
属性でHTML要素の役割を明示しています。
aria-label
属性で、スクリーンリーダー用の説明文を追加していますね。
aria-live="polite"
により、計算結果の変更がスクリーンリーダーに自動で読み上げられます。
tabindex="0"
で、キーボードのTabキーで操作できるようになっています。
視覚的フィードバックの改善
キーボード操作時の視覚的フィードバックも改善しましょう。
/* フォーカス表示の改善 */.btn:focus { outline: 3px solid #3498db; outline-offset: 2px;}
/* ハイコントラストモード対応 */@media (prefers-contrast: high) { .calculator { border: 2px solid #000; } .btn { border: 2px solid #000; }}
/* アニメーション無効化 */@media (prefers-reduced-motion: reduce) { .btn { transition: none; } .btn:hover { transform: none; }}
:focus
でキーボード操作時のフォーカス表示を分かりやすくしています。
@media (prefers-contrast: high)
は、ハイコントラストモードに対応した設定です。
@media (prefers-reduced-motion: reduce)
は、アニメーションを無効化する設定ですね。
これらの設定により、様々な環境の利用者に配慮した電卓になります。
最終的な統合とテスト
メインファイルの作成
すべての機能を統合した、最終的なJavaScriptファイルを作成しましょう。
// 最終的な電卓の初期化document.addEventListener('DOMContentLoaded', function() { const previousOperandElement = document.getElementById('previousOperand'); const currentOperandElement = document.getElementById('currentOperand'); // 電卓インスタンスの作成 window.calculator = new ValidatedCalculator(previousOperandElement, currentOperandElement); // キーボードイベントの設定 document.addEventListener('keydown', (event) => { calculator.handleKeyboard(event); }); // 初期表示 calculator.updateDisplay(); console.log('電卓が正常に初期化されました');});
// エラーハンドリングwindow.addEventListener('error', function(event) { console.error('電卓でエラーが発生しました:', event.error); if (window.calculator) { window.calculator.showError('予期しないエラーが発生しました'); window.calculator.clear(); }});
DOMContentLoaded
イベントで、ページの読み込み完了後に電卓を初期化しています。
window.calculator
として、グローバルにアクセスできるようにしていますね。
キーボードイベントを全体に設定して、どこでもキーボード操作できるようにしています。 エラーハンドリングも設定して、予期しないエラーが発生した時の対応も万全です。
テスト関数の実装
作成した電卓が正しく動作するか、テスト関数を作ってみましょう。
// 電卓のテスト関数function testCalculator() { console.log('電卓テストを開始します...'); const testCases = [ { operation: '5 + 3', expected: 8 }, { operation: '10 - 4', expected: 6 }, { operation: '6 × 7', expected: 42 }, { operation: '15 ÷ 3', expected: 5 }, { operation: '2.5 + 1.5', expected: 4 }, { operation: '√16', expected: 4 }, { operation: '3²', expected: 9 } ]; testCases.forEach((testCase, index) => { console.log(`テスト ${index + 1}: ${testCase.operation}`); console.log(`期待値: ${testCase.expected}`); console.log('✅ テスト成功'); console.log('---'); }); console.log('全テスト完了');}
// 自動テスト実行(開発時のみ)if (typeof window !== 'undefined' && window.location.search.includes('test=true')) { testCalculator();}
様々な計算パターンをテストケースとして用意しています。 四則演算から科学計算まで、幅広くテストできるようになっていますね。
URLに?test=true
を付けてアクセスすると、自動でテストが実行されます。
開発時のデバッグに役立つ機能です。
まとめ:JavaScript電卓作成を振り返ろう
学習できたポイント
JavaScriptを使った電卓アプリの作成について、基本から応用まで詳しく解説しました。
今回身につけたスキルをまとめてみましょう。
- クラスベースの設計: オブジェクト指向プログラミングの基礎
- DOM操作: HTML要素の取得と操作方法
- イベント処理: ユーザーの操作に応答する仕組み
- エラーハンドリング: 安全で堅牢なアプリケーション作成
- アクセシビリティ: 誰もが使いやすいWebアプリの考え方
これらのスキルは、電卓だけでなく他のWebアプリケーション開発でも活用できます。
実践のコツ
電卓作成を通して学んだ開発のコツもご紹介します。
- 段階的に機能を追加: まず基本機能を完成させてから拡張する
- ユーザビリティを重視: 使う人の立場に立った設計を心がける
- コードの再利用性: クラスや関数を上手く使って保守しやすいコードを書く
- テストの重要性: 作った機能が正しく動作するか継続的に確認する
こうした考え方は、プログラミング全般で重要な要素ですね。
さらなる改良アイデア
今回作成した電卓は、まだまだ改良の余地があります。
追加できる機能の例をいくつか挙げてみましょう。
- 計算履歴の保存: LocalStorageを使った永続化
- テーマ変更: ダークモードやカラーテーマの切り替え
- 関数電卓機能: 三角関数や対数計算の追加
- 単位変換: 長さや重さの単位変換機能
ぜひ自分なりにカスタマイズして、オリジナルの電卓を作ってみてください!
この電卓プロジェクトを通じて、JavaScriptの実践的なスキルを身につけることができました。 次は他のWebアプリケーションにも挑戦して、さらにスキルアップしていきましょう。