32
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptの「関数まわり」応用まとめ

Last updated at Posted at 2025-07-29

JavaScriptの「関数まわり」応用まとめ

~スコープ・関数式・高階関数・メソッド・this・エラーハンドリング~


🗺️ スコープとは?

スコープとは「変数や関数がどこから見えるか?」という “見える範囲” のこと。
どこで宣言したかによって、その変数が使える場所が決まります。


🔸 ブロックスコープ

letconstで宣言した変数は、{ } の内側だけ有効です。

{
  let message = "チョコレート";
  console.log(message); // → チョコレート
}
// console.log(message); // ← エラー:もう見えない

🔸 レキシカルスコープ

スコープは「書いた位置関係どおり」で決まります(実行の流れではなく“見た目”のネストで決まる)

let weather = '晴れ';
function showWeather() {
  let feeling = 'あったかい';
  console.log(weather); // → 晴れ(外側の変数が見える)
}
showWeather();
// console.log(feeling); // ← エラー:関数の外からは見えない

✏️ 関数式(function expression)

関数も「値」として変数に入れることができます。

const multiplyNumbers = function (x, y) {
  return x * y;
};

console.log(multiplyNumbers(3, 8)); // → 24

🚀 高階関数(Higher Order Function)

関数を引数にしたり、戻り値にする関数を「高階関数」と呼びます。

関数を“受け取る”高階関数の例

function repeatAction(action) {
  action();
  action();
}

function showSurprise() {
  const emoji = ['🎉', '🎁', ''][Math.floor(Math.random() * 3)];
  console.log(`サプライズ!${emoji}`);
}

repeatAction(showSurprise);
// サプライズが2回表示される

関数を“返す”高階関数の例

function createRangeChecker(min, max) {
  return function (value) {
    return value >= min && value <= max;
  };
}

const isTeenager = createRangeChecker(13, 19);
console.log(isTeenager(15)); // → true
console.log(isTeenager(22)); // → false

🛠️ メソッド(method)

オブジェクトの中の関数は「メソッド」と呼ばれます。

const calculator = {
  PI: 3.1415,
  square(num) {
    return num * num;
  },
  triple(num) {
    return num * 3;
  },
};

console.log(calculator.PI);         // → 3.1415
console.log(calculator.square(5));  // → 25
console.log(calculator.triple(7));  // → 21

🐾 thisキーワード

thisは「呼び出したオブジェクト自身」を指します。
同じオブジェクトの他のプロパティと連携したいときに大活躍!

const dog = {
  name: 'モカ',
  breed: 'トイプードル',
  bark() {
    console.log(`${this.name}がワン!と吠えました`);
  },
};

dog.bark(); // → モカがワン!と吠えました
  • thisが指すものは「呼び出し方」で決まる
    (単体で使う場合や関数の外など、想定外の挙動に注意!)

⚠️ try...catchでエラーに強いコードを書く

予期しないエラーもtry...catchでキャッチすればプログラムが止まりません。

try {
  icecream.flavor(); // icecreamは未定義→エラー
} catch {
  console.log('何か問題が起きたみたいです🍦');
}

console.log('プログラムは続行します');

→ 「エラーが出ても止まらず次の処理に進める」


📝 まとめ

  • スコープ:変数や関数の“見える範囲”
  • 関数式:関数も「値」として変数にできる
  • 高階関数:関数を受け取ったり返したりできる
  • メソッド:オブジェクトの中の関数
  • this:呼び出し元のオブジェクトを指す魔法のキーワード
  • try...catch:エラーが出ても慌てないプログラム
32
10
2

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
32
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?