-----------2-----------2-----------2-----------2-----------2-----------2-----------2-----------2-----------2--------
🔹 Using var
:
var
is function scoped, so inside the loop, each iteration shares the samei
setTimeout
is asynchronous, so the loop finishes before any of the callbacks run- By the time the callbacks execute,
i
is already3
- That’s why
3
is printed three times
🔹 Using let
:
let
is block scoped, meaning each loop iteration creates a fresh binding ofi
- Each
setTimeout
captures the current value ofi
- So it prints
0
,1
,2
— as expected
“var
behaves differently from let
, as it doesn't create a new variable for each loop iteration.”
var i
is function-scoped
Output:
So each arrow function captures a distinct copy of i
(0, then 1, then 2) Why 3 Output instead 2:
iteration 1: callback delays at this time i =0,
iteration 2: callback delays at this time i =1
iteration 3: callback scheduled at this time i =2 and executed after this so it is iterated again 3
iteration 2: callback delays at this time i =1
iteration 3: callback scheduled at this time i =2 and executed after this so it is iterated again 3
FINAL:
-------3--------3-----------3------------3---------3-------------3-------------3------------3----------
📘 console.log()
- Purpose: General-purpose logging
- Usage: For debugging, tracking values, or displaying routine messages
console.warn()
- Purpose: Signals a warning or potential issue
- Usage: Highlight deprecated code, suspect logic, or cautionary flags
--------4----------4---------4------------4----------4----------4-----------4-
-------5-------5----------5----------5----------5
----6-----6----6--------6-----------6------------6-------------6----------6----------6-------6----
1.Allocation to same memory and 2. Allocation to different memory with object.assign
Both c
and d
point to the same object in memory, which means any change to one reflects in the other.
You're not copying the contents of c
into d
. You're just copying the reference
Want to explore how to break that shared reference and create a copy instead? You can do it with spread syntax, Object.assign()
, or deep cloning techniques. Say the word!
------7------7---------7--------7--------7----------7------------7--------7------------7
<script>
var x;
let x=12;
console.log(x)
</script/>
---9---9---9---99--
10---10---10---10----10