1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

以下のコードがどのように実行されるか、コールスタックの動きに注目して超具体的に見ていきます。

function multiplay(x, y) {
    return x * y;
}

function square(x) {
    return multiplay(x, x);
}

function isRightTriangle(a, b, c) {
    return square(a) + square(b) === square(c);
}

console.log(isRightTriangle(3, 4, 5)); // true

今回は loap というツールを利用します。
コールスタック・Web API・コールバックキューの挙動が視覚的に見れる神ツールです

まずは以下の動画を丁寧に見てみてください

Videotogif (1).gif


この実行の流れを言葉で追ってみましょう

  1. isRightTriangle(3, 4, 5) が呼ばれる
     → isRightTriangle がコールスタックに積まれる

  2. isRightTriangle の中で square(3) が呼ばれる
     → square(3) がコールスタックに積まれる

  3. square(3) の中で multiplay(3, 3) が呼ばれる
     → multiplay(3, 3) がコールスタックに積まれる

  4. multiplay(3, 3) が計算され 9 を返す
     → multiplay(3, 3) がコールスタックから外れる

  5. square(3)9 を返す
     → square(3) がコールスタックから外れる

  6. isRightTriangle の中で次に square(4) が呼ばれる
     → square(4) がコールスタックに積まれる

  7. square(4) の中で multiplay(4, 4) が呼ばれる
     → multiplay(4, 4) がコールスタックに積まれる

  8. multiplay(4, 4) が計算され 16 を返す
     → multiplay(4, 4) がコールスタックから外れる

  9. square(4)16 を返す
     → square(4) がコールスタックから外れる

  10. isRightTriangle の中で次に square(5) が呼ばれる
     → square(5) がコールスタックに積まれる

  11. square(5) の中で multiplay(5, 5) が呼ばれる
     → multiplay(5, 5) がコールスタックに積まれる

  12. multiplay(5, 5) が計算され 25 を返す
     → multiplay(5, 5) がコールスタックから外れる

  13. square(5)25 を返す
     → square(5) がコールスタックから外れる

  14. isRightTriangle9 + 16 === 25 を評価し、true を返す
     → isRightTriangle がコールスタックから外れる

  15. console.log(true) が実行される
     → console.log がコールスタックに積まれる
     → 出力が終わり、console.log がコールスタックから外れる


まとめ

  • コールスタックに「積まれる → 外れる」の動きを追うことで、処理の正確な順序が見れます
  • この仕組みを理解すれば、思わぬバグやミスを減らせます

質問や疑問があればコメントにどうぞ!

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?