As a newcomer to JavaScript, I came across an intriguing problem that made me question what would be displayed on the console. The correct answer turned out to be 4 4 4 4
, thanks to pass-by-reference. Still, I'm struggling to grasp why this is the outcome. How does pass-by-reference come into play when the output seems to solely rely on the value of i
within a simple for-loop
iteration?
const array = [10, 21, 31, 41];
for(i = 0; i < array.length; i++) {
setTimeout(function print(array){
console.log(i)}, 3000);
}