以下のコードがどのように実行されるか、コールスタックの動きに注目して超具体的に見ていきます。
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・コールバックキューの挙動が視覚的に見れる神ツールです
まずは以下の動画を丁寧に見てみてください
この実行の流れを言葉で追ってみましょう
-
isRightTriangle(3, 4, 5)
が呼ばれる
→isRightTriangle
がコールスタックに積まれる -
isRightTriangle
の中でsquare(3)
が呼ばれる
→square(3)
がコールスタックに積まれる -
square(3)
の中でmultiplay(3, 3)
が呼ばれる
→multiplay(3, 3)
がコールスタックに積まれる -
multiplay(3, 3)
が計算され 9 を返す
→multiplay(3, 3)
がコールスタックから外れる -
square(3)
が 9 を返す
→square(3)
がコールスタックから外れる -
isRightTriangle
の中で次にsquare(4)
が呼ばれる
→square(4)
がコールスタックに積まれる -
square(4)
の中でmultiplay(4, 4)
が呼ばれる
→multiplay(4, 4)
がコールスタックに積まれる -
multiplay(4, 4)
が計算され 16 を返す
→multiplay(4, 4)
がコールスタックから外れる -
square(4)
が 16 を返す
→square(4)
がコールスタックから外れる -
isRightTriangle
の中で次にsquare(5)
が呼ばれる
→square(5)
がコールスタックに積まれる -
square(5)
の中でmultiplay(5, 5)
が呼ばれる
→multiplay(5, 5)
がコールスタックに積まれる -
multiplay(5, 5)
が計算され 25 を返す
→multiplay(5, 5)
がコールスタックから外れる -
square(5)
が 25 を返す
→square(5)
がコールスタックから外れる -
isRightTriangle
が 9 + 16 === 25 を評価し、true を返す
→isRightTriangle
がコールスタックから外れる -
console.log(true)
が実行される
→console.log
がコールスタックに積まれる
→ 出力が終わり、console.log
がコールスタックから外れる
まとめ
- コールスタックに「積まれる → 外れる」の動きを追うことで、処理の正確な順序が見れます
- この仕組みを理解すれば、思わぬバグやミスを減らせます
質問や疑問があればコメントにどうぞ!