JavaScript Problem: A Tricky JavaScript Interview Question

preview_player
Показать описание
In this tutorial we are going to look at a JavaScript problem that is sometimes used to weed out JS developers during a JavaScript interview. This problem shows the interplay of scope and closure.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

This video is such a superb example of improving deep understanding of javascript every step of the way. Much appreciated!

Hooghog
Автор

Such a great video once again! Thank you!!

ChrisTian-oxnr
Автор

I paused at the start and correctly predicted the unwanted behaviour. However, being lazy I ran the routine by directly typing into the browser console rather than saving and loading a document. I became frustrated as the result was 6, just 6, nothing else (not even the string part of the template literal). if I used the up arrow and re-ran the routine in console, the 6 incremented by 5 each time. When I ran it from a document it behaved as expected. I'm still scratching my head to work out why it was returning an integer when typed directly (any insight greatly appreciated).

The use of let in the outer loop to create closure is clever (and I had not predicted that but will not forget it!). My only other refinement, a minor point, was to change the milliseconds interval to 2000*(1+i) to make the console logs sequentially over 5 two-second intervals, as I assumed that was the intention.

Excellent discussion, especially reasoning through the stages. Thanks. 💯

batchrocketproject
Автор

We can also get the expected result using bind:


const arr = [5, 10, 15, 20, 25];

for (var i=0; i<arr.length; i++) {
setTimeout(function(i){
console.log(`Index: ${i}, element: ${arr[i]}`)
}.bind(null, i), 2000);
}

zameeebasha
Автор

Pls do video series on "Tricky Javascript Interview Questions" this topic

arunkaiser
Автор

Also works with a third argument of setTimeout function

Chantaletecker
Автор

Thank you SIR, i got it now, what's with the third argument in the setTimeout function?

chamnil
Автор

I used let for variable declaration the loop completely working after 2s

uthirapathikuppusamy
Автор

What if the task is to show each of the results every 2 seconds? Why not use sync/await?

KatieGeorgieva
Автор

I do not get why it still does not work even if I change 2000 to zero inside the set time out.

wilsonfaustino
join shbcf.ru