From 455cf31e421af8796490c2ea6e41960629258d30 Mon Sep 17 00:00:00 2001 From: KhotKeys Date: Wed, 12 Aug 2026 16:28:39 +0100 Subject: [PATCH] Answer code reading questions --- debugging/code-reading/readme.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/debugging/code-reading/readme.md b/debugging/code-reading/readme.md index 4090c14c6..2e69c9ef9 100644 --- a/debugging/code-reading/readme.md +++ b/debugging/code-reading/readme.md @@ -17,6 +17,10 @@ Take a look at the following code: Explain why line 5 and line 8 output different numbers. +## Answer 1 + +Line 5 outputs `2` and line 8 outputs `1` because of scope. The `x` declared inside `f1` on line 4 is a separate variable that only exists within that function. It shadows the outer `x`. When `f1` finishes, the inner `x` is gone, so line 8 reads the outer `x` which is still `1`. + ## Question 2 Take a look at the following code: @@ -35,6 +39,16 @@ console.log(y); What will be the output of this code. Explain your answer in 50 words or less. +## Answer 2 + +The output is: +``` +10 +undefined +ReferenceError: y is not defined +``` +`f1()` logs `10` (the outer `x`) but returns `undefined` since there is no return statement, so `console.log(f1())` prints `undefined`. Then `console.log(y)` throws a `ReferenceError` because `y` is declared inside `f1` and not accessible outside it. + ## Question 3 Take a look at the following code: @@ -62,3 +76,12 @@ console.log(y); ``` What will be the output of this code. Explain your answer in 50 words or less. + +## Answer 3 + +The output is: +``` +9 +{ x: 10 } +``` +Primitives like numbers are passed by value, so `f1` cannot change the original `x`. Objects are passed by reference, so `f2` mutates the original `y` object directly, changing `y.x` from `9` to `10`.