JavaScript Coding Challenge: Closures and Memory Context

#JavaScript !! Coding Challenge !! Can you guess the output of the following code — and explain why? function outer() {  const data = { count: 0 };   return function inner() {   data.count++;   return data.count;  }; } const first = outer(); const second = outer(); first(); first(); second(); console.log(first(), second()); 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧 -  What will this print in the console — and what’s happening behind the scenes? 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲𝐬: Think carefully about closures, memory context, and whether first and second share the same reference or not. 𝐃𝐫𝐨𝐩 𝐲𝐨𝐮𝐫 𝐚𝐧𝐬𝐰𝐞𝐫 (𝐚𝐧𝐝 𝐫𝐞𝐚𝐬𝐨𝐧𝐢𝐧𝐠!) 𝐢𝐧 𝐭𝐡𝐞 𝐜𝐨𝐦𝐦𝐞𝐧𝐭𝐬. #JavaScript #Closures #WebDevelopment #CodingChallenge #Frontend #JSInterview

It will print 3 and 2 because the inner function forms a closure with data.count from the outer function. So it maintains the count reference in the memory and increments by 1. Also first and second do not share the same reference .

To view or add a comment, sign in

Explore content categories