JavaScript for-loops are… complicated - HTTP203

แชร์
ฝัง
  • เผยแพร่เมื่อ 6 ส.ค. 2018
  • In this episode, Jake and Surma dissect how for-loops actually work and how they’ve evolved. Turns out, it got complicated.
    Subscribe to the channel! → bit.ly/ChromeDevs1
    Watch more HTTP203 → bit.ly/2sPq2LB
    Listen to the HTTP203 podcast for more content! → bit.ly/2Kryv2y
    Itunes → apple.co/2IQagG6
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 248

  •  6 ปีที่แล้ว +121

    I’m just waiting for the next big data leak to be the result of a for loop vulnerability.

    • @JustGetWithIt2013
      @JustGetWithIt2013 6 ปีที่แล้ว

      Well that is why you do code testing in multiple ways. At times developers are eager to launch a project or fix

  • @Norfeldt
    @Norfeldt 3 ปีที่แล้ว +22

    The discussion and topic is great. If it had some console.log results shown I would have been more easily following the discussion.

  • @DebabrataAcharya93
    @DebabrataAcharya93 6 ปีที่แล้ว +17

    "If you format your code like this I'm gonna slap you." 😂

  • @lb3724
    @lb3724 6 ปีที่แล้ว +187

    Super interesting but I have one complaint - I wish you would take care to show the screen for longer periods and more often. Especially when one of them is actually pointing at the screen explaining stuff and you're still on their faces so we can't even see what part of the code they are referencing. Showing their faces helps break up video in a pleasing way but it provides no education value.

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว +31

      Good feedback. Will pass it on to the editors and will watch out for it in future cuts.

    • @dassurma
      @dassurma 6 ปีที่แล้ว +36

      Maybe we can attach the tablet to my face?

    • @lb3724
      @lb3724 6 ปีที่แล้ว +4

      Surma are you feeling attacked by my feedback?

    • @dassurma
      @dassurma 6 ปีที่แล้ว +6

      Not at all! Sorry if it came across that way. As Jake said, it's super helpful for us.

    • @victornpb
      @victornpb 6 ปีที่แล้ว

      I up that

  • @GmoneyMozart
    @GmoneyMozart 6 ปีที่แล้ว +39

    This was fun. More videos like this!

  • @StarCoreSE
    @StarCoreSE 5 ปีที่แล้ว +11

    JavaScript is very good at making simple things become complex, for simplicity purposes...

  • @ngneerin
    @ngneerin 3 ปีที่แล้ว +1

    Love this series. Do more of these

  • @AlekseyNew
    @AlekseyNew 6 ปีที่แล้ว +11

    It was cool. I missed valuable videos like this one.

  • @mikehallishere
    @mikehallishere 6 ปีที่แล้ว +57

    Not so much that for-loops are complicated, more that closures and scoping is complicated.

    • @taragnor
      @taragnor 6 ปีที่แล้ว +6

      Yeah, closures, scoping and asynchronous programming. That's a complex mix of things.

    • @felixp535
      @felixp535 5 ปีที่แล้ว +1

      Uh uh, Javascript makes closures and scoping complicated. It's actually not that difficult

  • @AndrewLuhring
    @AndrewLuhring 6 ปีที่แล้ว

    I gotta say, i thought this was going to make my brain implode, and it did but not as much as i expected it to. gj jake and surma

  • @sreelalts1892
    @sreelalts1892 6 ปีที่แล้ว +3

    Really complicated ::: Oh God! Jake and Surma... That was a really helpful one. Thanks :)

  • @Challenge9000
    @Challenge9000 6 ปีที่แล้ว

    Learned so much, thank you.

  • @kosnk
    @kosnk 3 ปีที่แล้ว +1

    Thanks to you, I found that eval('for(let i=0; i

  • @ElektrykFlaaj
    @ElektrykFlaaj 2 ปีที่แล้ว +1

    This channel is like Numberphile for web developers

  • @girlswithgames
    @girlswithgames 5 ปีที่แล้ว +25

    videos like these make me want to unlearn programming

  • @AbhishekKumar-mq1tt
    @AbhishekKumar-mq1tt 6 ปีที่แล้ว

    Thank u for this awesome video

  • @karlheinzneugebauer
    @karlheinzneugebauer 6 ปีที่แล้ว +2

    Meine Güte! Da wird die Wartung von fremdem Code noch ein Stück "lustiger" :O

  • @DenisTRUFFAUT
    @DenisTRUFFAUT 6 ปีที่แล้ว

    Wow. Mind blowing.

  • @sangeeth96
    @sangeeth96 6 ปีที่แล้ว +2

    I recently stumbled upon this bit of info (from Kyle Simpson IIRC) which talked about function parameters having their own context and stuff. I was wondering since there is a new `for await` syntax and generators and all kinds of things, could we have like a whole redo on "scope, contexts and closures" with all the ES* features and the under-the-hood on how these concepts are different now? Would love to see that on this series or in some other form on this channel.

  • @sy-hungdoan4859
    @sy-hungdoan4859 3 ปีที่แล้ว

    Awesome !!! I literally unlearnt for loops

  • @giacmoit
    @giacmoit 5 ปีที่แล้ว

    Awesome, it's really helpfull

  • @jayakrishnanjr5194
    @jayakrishnanjr5194 5 ปีที่แล้ว

    This is awesome

  • @LA-MJ
    @LA-MJ 6 ปีที่แล้ว

    I am not sure if I should be worried that none of this surprised me, except the fact that update check is considered to be the start of the iteration.

  • @LeandroCoutinho
    @LeandroCoutinho 6 ปีที่แล้ว

    amazing crazy stuff

  • @ColinRichardson
    @ColinRichardson 6 ปีที่แล้ว +2

    I use bare blocks (thanks for the name), in both Javascript and Java.. Very useful to help setup a variable you want to keep but throw away the helping variables (or in most cases, use the same named variable but with different types)

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว +1

      I really like the "do blocks" proposal for this

  • @SurvTech
    @SurvTech 4 ปีที่แล้ว

    This is soo cool.

  • @slavkokovljenic6621
    @slavkokovljenic6621 6 ปีที่แล้ว +1

    Interesting stuff..just one thing, make sure the presentation of the code LAST LONGER on the video and also highlight the part with red circles when he is pointing to a specific part of the code..

  • @adithyareddy6211
    @adithyareddy6211 6 ปีที่แล้ว +9

    This hurt my brain

  • @HashimWarren
    @HashimWarren 6 ปีที่แล้ว +4

    weirdly entertaining

  • @wmhilton-old
    @wmhilton-old 6 ปีที่แล้ว +6

    1:52 - I should have known Jake would pull out "setTimeout". That's like your thing now, isn't it? Jake "the Event Loop" Archibald presents... :-)

    • @NICHLE.
      @NICHLE. 5 หลายเดือนก่อน

      Yeah, that was one of the greatest presentations ever on the inner workings of JavaScript." Do you know any other similiar web related stuff like this one?

  • @MartinOckovsky
    @MartinOckovsky 6 ปีที่แล้ว +1

    You guys are great!

  • @pragyandas
    @pragyandas 6 ปีที่แล้ว

    I wish they showed and explained the lexer code. Off the records, Y Combinator for life 😊

  • @jeremykothe2847
    @jeremykothe2847 5 ปีที่แล้ว

    I get that it's his first reaction, but going from... a) incorrectly answering what the original code would do, exposing one of the more common bugs for intermediate JS coders, the "modified closure"... to being shown an elegant no-brain solution to it and reacting with..... b) "don't". is something he'll revisit if he hasn't already. The alternative is to wrap the body of the loop in a function and pass "i" in, which is what we used to have to do to solve this problem.

  • @yixunnnn
    @yixunnnn 6 ปีที่แล้ว +1

    I came in thinking I understood loops, I came out knowing I understand nothing.

  • @aperson4051
    @aperson4051 4 ปีที่แล้ว

    Does the first example (with 'var i') return 2, 2 times, because the delay before execution means the loop will have finished already, or is it a different mechanism that returns 2?

  • @b3rakesh11
    @b3rakesh11 6 ปีที่แล้ว

    Awesome

  • @amritasinghg72
    @amritasinghg72 4 ปีที่แล้ว

    Hey @Jake and @Surma. I was following this video pretty much attentively. Just the last thing right there using setTimeOut() as an initialiser in for loop, not able to understand that part tried google it but I guess no one reached there yet :P. So can you please tell me how it actually worked to print 0.

  • @carloslfu
    @carloslfu 4 ปีที่แล้ว

    hahaha, so funny! great job guys :)

  • @krisztianvarga4137
    @krisztianvarga4137 6 ปีที่แล้ว +1

    Perfect examples for "If you can do something that doesn't mean you should." ..I just fail to see how the intricacies of for loop help a team to create valuable code. The video itself was interesting though :)

    • @Cybolic
      @Cybolic 5 ปีที่แล้ว

      I take it as a healthy reminder: "If this is confusing you, read up on scopes and closures; also, generally just use for-of".

  • @hypersonic12
    @hypersonic12 6 ปีที่แล้ว

    So for cases at scale (lots of iterations with a small amount of work happening in each iteration), is it better to use var vs. let to avoid all the copy overhead each iteration?

    • @dassurma
      @dassurma 6 ปีที่แล้ว +3

      I think the JavaScript engine takes good care of you. It’s probably not worth thinking about the performance difference between the two. But you wanna check, measure. “Tools, not rules”.

  • @kosnk
    @kosnk 3 ปีที่แล้ว

    I love how Jake and Surma pretend that one of them doesn't know about the all time most famous "for loop w/ setTimeout" question that is asked on every single interview. Acting at 120% :)

  • @jasonguo7596
    @jasonguo7596 5 ปีที่แล้ว +1

    The var vs. let setTimeout examples can be really confusing.
    If the presenters showed the ES5 version of the code, it would make a lot more sense especially to the beginners.
    I used webpack to transpile the ES6 version source code to ES5.
    ES6:
    for ( let i = 0; i < 2; i += 1) {
    setTimeout(() => {
    console.log(i);
    }, 0);
    }
    Becomes ES5:
    var _loop = function _loop(j) {
    setTimeout(function () {
    console.log(j);
    }, 0);
    };
    for (var i = 0; i < 2; i += 1) { _loop(i); }
    In ES5 code, we are invoking the _loop() function during each of the for-loop iteration.
    Because the _loop() function is invoked with the value of i, therefore the value of i is copied to the new lexical scope which is created by the _loop() function.
    Eventually the function setTimeout() is invoked inside the lexical scope of the _loop() function where the variable j holds the copied value of i.

    • @jakearchibald
      @jakearchibald 5 ปีที่แล้ว

      Unfortunately that ES5 example isn't quite the same as how let works. For instance, the ES5 example gives you i in the parent scope.

    • @jasonguo7596
      @jasonguo7596 5 ปีที่แล้ว

      Hello Jake,
      Thank you for replying.
      Are there any resources where we can read about this topic? Or how did you came about understanding the concept?

    • @jakearchibald
      @jakearchibald 5 ปีที่แล้ว

      I experimented with it (the examples in the video) and read the specification.

  • @codingmaster6321
    @codingmaster6321 6 ปีที่แล้ว

    YEY ! google got a new sub !

  • @DataPlumber
    @DataPlumber 6 ปีที่แล้ว +19

    This sounds like a minefield for any transpiler trying to mimic this sort of thing with var isn't is?

    • @mihaimanole2643
      @mihaimanole2643 6 ปีที่แล้ว

      I don't find any danger in var usage because is an old and well understood behavior. The let in for is tricky, as I see.

    • @davec4197
      @davec4197 6 ปีที่แล้ว +1

      You can type the code into babeljs.io/repl to see how it's transpiled -function scope is used for the same effect as let in a for loop header.

    • @zekicay
      @zekicay 6 ปีที่แล้ว

      And it doesn't work correctly with the last example - it outputs "2"

  • @pdcx
    @pdcx 2 ปีที่แล้ว

    cool stuff. essentially multiple {} zones in for loop's ()

  • @sandeeptottadi
    @sandeeptottadi 2 ปีที่แล้ว

    Had fun😄😄🤣

  • @aidanbrumsickle
    @aidanbrumsickle 5 ปีที่แล้ว

    So basically you have this?
    for (let i = 0; i < n; i++) {
    // body
    }
    Becomes:
    {
    let i_;
    let t_;
    {
    let i = 0;
    i_ = i;
    t_ = i < n;
    }
    while (t_) {
    let i = i_;
    //body
    i++;
    i_ = i;
    t_ = i < n;
    }
    }
    Where i_, t_ are some gensym / guaranteed free variables?

  • @wonder.5400
    @wonder.5400 6 ปีที่แล้ว +3

    Gotta love JS. Not gonna lie, it is growing so much and being used in so many more ways than before.

    • @wonder.5400
      @wonder.5400 6 ปีที่แล้ว

      randomguy8196 web assembly is pretty good. It’s pretty much like a virtual machine for the web. But since it’s restricted to the web, that’s why I’m seeing JS as a Lang that is being used more in other things .

  • @derstreber2
    @derstreber2 6 ปีที่แล้ว

    Javascript is incredibly easy for beginners, and is also a powerful tool for professionals.... as long as you don't use for loops... or let... or var... or closures... or semicolons... or ==... or .........

    • @autorashades1984
      @autorashades1984 5 ปีที่แล้ว

      Doesn't sound like you know what you are talking about.

  • @BobbyBundlez
    @BobbyBundlez 3 ปีที่แล้ว

    for(let i=0; iconsole.log(i))
    i++
    }
    this confuses the shit out of me. would NEVER have expected that to just be 1

  • @mattscheurich1037
    @mattscheurich1037 5 ปีที่แล้ว

    I thought the whole point of using a for-loop compared to Array.forEach is that you can abort the for-loop using `break` (and skip items using `continue`), which can (depending on what you're doing) optimise your code performance. Now that for-loops are doing all this crazy extra lexical scope jiggery-pokery, does it affect their performance? Probably not significantly, but I'm still a bit weirded out by the lexical scope variable cloning!

  • @royyair6501
    @royyair6501 6 ปีที่แล้ว +2

    8:39
    "we do our ++ on it,
    i is now 2,
    we do our check
    it is not less than 2"
    wait what??

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      Yeah. If i is 2, it is not less than 2 :D

    • @royyair6501
      @royyair6501 6 ปีที่แล้ว

      it is :)
      its just that he had this tone and body language of: "it is not less than 2" ...the condition is falsy and therefore the loop continues

    • @joseluis8291
      @joseluis8291 6 ปีที่แล้ว

      *therefore the loop do not continue

  • @srsajjad7460
    @srsajjad7460 6 ปีที่แล้ว

    man ! this episode was dark

  • @damians.7859
    @damians.7859 ปีที่แล้ว

    One year later I still get lost, maybe next year

  • @vladyaremenko7945
    @vladyaremenko7945 6 ปีที่แล้ว +1

    Where are you find all of this nuances?
    I'm just trying to find it in the ECMA specification www.ecma-international.org/ecma-262/9.0/index.html#prod-ForDeclaration and I can see nothing like this

  • @kgarbaya
    @kgarbaya 6 ปีที่แล้ว +9

    Does this mean that for(var i) is faster than for(let i) because it's creating a new var in
    every iteration ?

    • @dassurma
      @dassurma 6 ปีที่แล้ว +27

      Don’t underestimate the amount and sophistication of the optimizations a JavaScript engine. In 99.9% of the cases, it’s not worth thinking about the performance differences (if there is any).

    • @kgarbaya
      @kgarbaya 6 ปีที่แล้ว

      Agree Surma, but i was just wondering

    • @brianolsen5435
      @brianolsen5435 6 ปีที่แล้ว +4

      Maybe using "let" will make your code take long enough to execute that it gets recompiled and optimized! Maybe "let" will be faster... because it is slower!
      What a strange world we live in.

    • @BenWeigt
      @BenWeigt 6 ปีที่แล้ว

      It's worth checking in certain cases however. I expected the difference between splicing and pushing to be negligible thanks to lower opts in some fairly heavy tree flattening / syncing code, however we found edge casing for push to be orders of magnitude faster.

  •  6 ปีที่แล้ว

    When the use of a programming language has "conditions" of use in itself, we maybe have a problem.

  • @azwanabdullah7750
    @azwanabdullah7750 6 ปีที่แล้ว

    If I could understand all of these 😩

  • @salasiapro
    @salasiapro 5 ปีที่แล้ว +1

    Great Thanks. Though I would have wished the screen would focus more on the code than your faces. Got lost once or twice

  • @HarryBallsOnYa345
    @HarryBallsOnYa345 ปีที่แล้ว

    10:35 Nice 🤣👍 tbh idek you could do this 👏

  • @uhl7792
    @uhl7792 6 ปีที่แล้ว

    The browser adds a buffer to setTimeout!! TIL!

  • @BertVerhelst
    @BertVerhelst 6 ปีที่แล้ว

    I wish you guys would go into the reasons why async await doesn't work as expected inside a far loop.

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      What do you expect it to do vs what it does?

    • @BertVerhelst
      @BertVerhelst 6 ปีที่แล้ว

      Jake Archibald I would expect await fnc() to complete before the next for loop iteration starts

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      That's how it should work. Can you give me a piece of code where it behaves differently?

    • @BertVerhelst
      @BertVerhelst 6 ปีที่แล้ว +2

      Wow, you're right. I was under the false assumption this wasn't possible. This is going to make my life so much easier :D
      Code sample for anyone that cares: codepen.io/bertyhell/pen/zLbdoQ?editors=0011

  • @uhl7792
    @uhl7792 6 ปีที่แล้ว

    What program is that you use to show code on the tablet?

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      Some bits of that infamous hand-crafted Jake code

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว +2

      Although, at the root of it, it's just Chrome. http203.glitch.me/ - click on the right-hand side of the screen to advance.

  • @dasten123
    @dasten123 5 ปีที่แล้ว

    Wow... just wow xD

  • @mrgerbeck
    @mrgerbeck 6 ปีที่แล้ว

    Haven't deliberately used a for-loop in years.

  • @bdjeosjfjdskskkdjdnfbdj
    @bdjeosjfjdskskkdjdnfbdj 5 ปีที่แล้ว

    need the draw the enviroment model haha

  • @devashish887
    @devashish887 3 ปีที่แล้ว

    Saying that its a new variable
    I don't see that right
    It's just for all iteration a new lexical scope created And passed the reference to closure
    In case of let there were so many lexical scope created
    Instead for var global scope reference remains same

  • @spiritlevelup1036
    @spiritlevelup1036 6 ปีที่แล้ว

    What did they say at the end? Sounded like use for-of 13:43

    • @jorgeibacache8229
      @jorgeibacache8229 5 ปีที่แล้ว +1

      developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

    • @spiritlevelup1036
      @spiritlevelup1036 5 ปีที่แล้ว +1

      Thank you! this explains why my javascript foreach(var a in list) is always failing hahahaha

  • @AnupRai11894
    @AnupRai11894 6 ปีที่แล้ว

    Hey had a doubt
    ```
    for(let j={a:0}; j.a console.log(j.a), 10);
    }
    Prints:
    3
    3
    3
    ```
    so copying is shallow for mutable types???

    • @AnupRai11894
      @AnupRai11894 6 ปีที่แล้ว

      what does the spec tells us about this??

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      There's still a new j in each iteration, and the value of j is assigned to the new j between each iteration, but the object itself isn't cloned.

    • @bendtherules0
      @bendtherules0 4 ปีที่แล้ว

      Exactly. It copies "by reference", if that makes sense. Basically do - let i = oldscope.i, in every new scope.
      No shallow clone.

  • @thebombus
    @thebombus 6 ปีที่แล้ว

    so just use "for" loops to create an array and then .map for intuitive results?

    • @denisolsem8418
      @denisolsem8418 6 ปีที่แล้ว

      With ES6 you can create an array of size N in one line without a for loop like this: const arr = [...Array(N)].map(your_callback)

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      Yeah, the functional approach always works. It can sometimes be preferable to use a for loop when using async/await. But even then the results are barely ever unintuitive.

  • @thomasmcguire3294
    @thomasmcguire3294 4 ปีที่แล้ว

    If 'let' is being recreated and copied over each iteration, wouldn't it be less performant compared to its 'var' declaration counterpart?

  • @BobLoblaw69
    @BobLoblaw69 6 ปีที่แล้ว

    So you recommend using for...of loops, while completely glossing over the fact that they are basically the least performant looping mechanism available in ECMAScript? A for...of loop is orders of magnitude slower than a standard C-style for loop, which itself is about 4x slower than a reversed for loop.

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      It is extremely unusual for the type of loop to be the performance bottleneck. The performance of looping tends to pale into insignificance vs the content of the loop body.

    • @BobLoblaw69
      @BobLoblaw69 6 ปีที่แล้ว

      It may not be a bottleneck, but a faster loop is a faster loop regardless. This becomes objectively more important when dealing with very large datasets. It is absolutely something every good programmer should always keep in mind.

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      It'd be even faster if you wrote it all in raw web assembly. Will you?

    • @BobLoblaw69
      @BobLoblaw69 6 ปีที่แล้ว

      I hadn't thought of that, as I don't completely understand web assembly yet. If I find that to be true, then I would probably start using C++. Very good point. Thank you for making me think about that.

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      Just for completeness sake: Where are you getting the “4x slower”? Recent benchmarks show for-of to be on-par with an old-school for-loop.

  • @RomanLyubimov
    @RomanLyubimov 3 ปีที่แล้ว

    But why is this:
    for (let i = 0; i < 4; i++) {
    setTimeout(() => console.log(i));
    i++;
    }
    Gives 2 1 3..

  • @RichardBuckerCodes
    @RichardBuckerCodes 6 ปีที่แล้ว

    what happened to the path of least surprise?

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      I think that goal is fulfilled here. You should barely ever encounter these corner cases that we are focusing on. They needed to weigh up maintaining let/const semantics vs making a for loop work as expected.

  • @BabekNagiyev
    @BabekNagiyev 4 ปีที่แล้ว

    I think Google should hire everyone who liked this video ;)

  • @neHCuoHEpa8888
    @neHCuoHEpa8888 6 ปีที่แล้ว

    HI, do anybody know is it same for swift?

    • @pardal_bs
      @pardal_bs 3 ปีที่แล้ว

      Probably not

  • @boheem3451
    @boheem3451 3 ปีที่แล้ว

    The setTimeout function in the first example is totally confusing. That seems to have nothing to do with the complications of the for-loop. In the browser setTimeout is mangled and clamped and security massaged.

    • @jakearchibald
      @jakearchibald 3 ปีที่แล้ว

      The browser doesn't mangle setTimeout calls. Nor does it give it any kind of massage that I'm aware of. setTimeout is used in this example to run the code after other code.

    • @boheem3451
      @boheem3451 3 ปีที่แล้ว

      @@jakearchibald I am not sure why you used setTimeout to illustrate the problem for-loops. That seems to add an extra layer of blackboxery. Something to do with the synchronous nature of javascript and the event loop. I don't think it helps to explain the subtleties of for-loops. Why did you use setTimeout? My intuition was that setTimeout was doing something 'in the background' I didn't understand. If you takeout setTimeout out of your examples would it still be useful as an example - pure for-loop with just an incrementing i variable?

    • @jakearchibald
      @jakearchibald 3 ปีที่แล้ว

      @@boheem3451 my intention was to delay execution to show which other code it shares a scope with

  • @lv85huenex
    @lv85huenex 5 ปีที่แล้ว

    so that was a funny intro

  • @wombora
    @wombora 6 ปีที่แล้ว +1

    Oh god, the intro sound is so strange on 100% speed - i subscribed to the podcast and play on 125% to 150% - and thats how i know the intro, and i think it sounds better speed up

  • @justind6983
    @justind6983 6 ปีที่แล้ว +3

    Sooooo, JavaScript behaves like statically typed languages in the instance of let being in the for loop.

    • @APaleDot
      @APaleDot 6 ปีที่แล้ว +3

      The weirdness here has little to do with statically vs. dynamically typed. The weirdness comes from the fact that the setTimeout function executes it's callback after the rest of the code has executed because it's an asynchronous task. So, the memory holding the i variable gets mutated, then the console.logs execute all at once after the for loop has finished.

    • @justind6983
      @justind6983 6 ปีที่แล้ว +1

      Thanks for further clarification. Seems being comfortable with async/await and/or promises is a must when working in Javascript? I haven't wrapped my tiny head around these concepts yet, but I am working on it. Thanks again.

    • @dassurma
      @dassurma 6 ปีที่แล้ว +2

      Yeah, definitely spend some time grasping promises and then async/await. Every modern API uses promises and they are great once you get comfortable with them.

  • @poloska9471
    @poloska9471 5 ปีที่แล้ว +12

    As much as I love it, JavaScript is an absolute disaster.

  • @nenadvicentic
    @nenadvicentic 6 ปีที่แล้ว +1

    Or I misunderstood, or you explained it wrong, for the `let` case? This is the result:
    for (let i = 0; i < 2; i++) {
    setTimeout(() => console.log(i));
    i++;
    }
    0
    1

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว +8

      This is an interesting gotcha - I'm guessing you ran this in the console? The 0 you're seeing isn't a console log, it's what the console determines as the result of the expression.
      Eg, if you run `1 + 2` in the console, it'll display 3. It isn't a console log, it's just the result.
      In that for-loop, the console takes the final expression as the result, which is the final `i++`, which evaluates to `i` before incrementing. This becomes more obvious if you do:
      for (let i = 0; i < 2; i++) {
      setTimeout(() => console.log('this is the real log', i));
      i++;
      }
      Which, if you paste it straight into the console, displays:
      0
      "this is the real log" 1

    • @nenadvicentic
      @nenadvicentic 6 ปีที่แล้ว +3

      Ah, right! It's clearly shown that `0` result, having `

    • @SebastiaanDeckers
      @SebastiaanDeckers 6 ปีที่แล้ว

      @Jake were you saying the i never gets logged? I have some trouble understanding the conversation at that point.
      Run in node 10.7.0 (v8: '6.7.288.49-node.15')
      I'm seeing: loop body logs 1, repl returns undefined, and loop head timeout logs 0
      > for (let i = (setTimeout(() => console.log('dory', i)), 0); i < 2; i++) console.log('dandy', ++i)
      dandy 1
      undefined
      > dory 0

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว +2

      What you're seeing there is what I'd expect.

    • @SebastiaanDeckers
      @SebastiaanDeckers 6 ปีที่แล้ว +2

      Thanks for clarifying! And thanks to both of you for being super responsive all over these comments. 🙏🏻

  • @Abhishek-dp5tc
    @Abhishek-dp5tc 3 ปีที่แล้ว

    I still dont understand this
    for(let i=0; i console.log(i))
    console.log(i)
    }

  • @FauzulChowdhury
    @FauzulChowdhury 6 ปีที่แล้ว

    So now, we are missing the *pointer.

  • @dwengs
    @dwengs 6 ปีที่แล้ว

    Of course I'm a little confused.

  • @liam9107
    @liam9107 6 ปีที่แล้ว +2

    The imposter syndrome is real after watching this

    • @BobbyBundlez
      @BobbyBundlez 3 ปีที่แล้ว

      u have a job? ive been studying a year and i knew like hALF this stuff. still feel like an idiot lol

  • @kressckerl
    @kressckerl 6 ปีที่แล้ว +2

    Squeaky voice: "I just lost all my credibility" xD

  • @Brondahl
    @Brondahl 6 ปีที่แล้ว

    @GoogleChromeDevelopers, @Google Chrome Developers, '@Google Chrome Developers', @'Google Chrome Developers' (sorry - I don't know how @ works with spaces :) )
    An 'old school' for loop can be converted into a while loop really easily, right?
    for(var iterator = initialiseFunc; testFunc; incrementFunc) { bodyFunc }
    behaves *exactly* as:
    var iterator = intialiseFunc();
    while(!testFunc()) {
    bodyFunc();
    incrementFunc();
    }
    Is it possible to "convert" a let for loop in the same way, to write out in standard JS what it does, as a while loop?
    And is it fundamentally special casing a 'for-let' loop as different from a 'for-var' loop? Or is it doing the *same* thing in both cases, but constructed so that it *behaves* differently.

    • @btcForum
      @btcForum 5 ปีที่แล้ว

      you can read about this here www.confusenerd.xyz/tech_post/loop_in_js/

  • @Noopkat
    @Noopkat 6 ปีที่แล้ว +2

    😂👏

  • @driziiD
    @driziiD 3 ปีที่แล้ว +1

    wow, i really don't like that even 'for' loops are complicated in JS

    • @sanjarcode
      @sanjarcode ปีที่แล้ว

      It's complicated when done on purpose.
      Normally, use can ignore this.

  • @threestar4045
    @threestar4045 6 ปีที่แล้ว

    What a rich and wonderful language!

  • @entalpa
    @entalpa 6 ปีที่แล้ว +2

    it;s not the incrementor, it's the update

    • @dassurma
      @dassurma 6 ปีที่แล้ว

      I guess that makes sense.

    • @bendtherules0
      @bendtherules0 4 ปีที่แล้ว

      The spec does call it "increment".
      But yeah, technically just a expression.

  • @liranh85
    @liranh85 6 ปีที่แล้ว +2

    I tried to wipe off the smudge off my screen for about 10 seconds before realising it's actually on your tablet and not on my screen... :|

  • @joseluis8291
    @joseluis8291 6 ปีที่แล้ว +3

    I tested the first examples and for (var i = 0; i < 2; i ++) { setTimeout(console.log(i)) } prints exactly the same as for (let i = 0; i < 2; i ++) { setTimeout(console.log(i)) } The result is the same, always (Google chrome over a Mac). So what is the difference?

    • @andrewli4484
      @andrewli4484 6 ปีที่แล้ว +12

      José Luis It should be setTimeout(() => console.log(i)) which creates the closure over i and passes an arrow function to setTimeout, or else you're immediately executing console.log on every iteration and passing undefined (which is because console.log doesn't return anything) to setTimeout without any closure trickiness

  • @frknaydn
    @frknaydn 6 ปีที่แล้ว

    13:34 I wrote the code but it returns 35772 not 0. Am i wrote wrong ?
    prnt.sc/kg5v6c

    • @jakearchibald
      @jakearchibald 6 ปีที่แล้ว

      Your code isn't quite the same. You've made the 0 an argument to setTimeout. Here's the code I used jsbin.com/jisojaq/edit?js,console.

    • @frknaydn
      @frknaydn 6 ปีที่แล้ว

      oww. i see. my mistake :)

  • @Benimation
    @Benimation 6 ปีที่แล้ว

    If you ever need any of this.. You probably don't..

    • @maowtm
      @maowtm 6 ปีที่แล้ว

      Benimation Have you ever tried to access variables controlled by for-loop asynchronously?

  • @sanjarcode
    @sanjarcode ปีที่แล้ว

    I hate people who ask such questions in interviews (except in case you're implementing this).
    Similar to this is post and pre increment in C++ in the same expression. In one word: cognitive disaster

  • @tiedye001
    @tiedye001 6 ปีที่แล้ว

    y tho

  • @daniellosbarillas6803
    @daniellosbarillas6803 6 ปีที่แล้ว

    Busters

  • @nmertsch8725
    @nmertsch8725 6 ปีที่แล้ว +8

    Why the heck is JS so popular, even though it is so weirdly designed? Sure, it has rules, and yes, it is possible to learn all this, but who thought that this mess of a language would be a great tool?

    • @maowtm
      @maowtm 6 ปีที่แล้ว +3

      Nimmer Mehr I personally think this is not complicated and the rules for for-loops make a lot of sense

    • @dassurma
      @dassurma 6 ปีที่แล้ว +4

      Just because it has weird corners doesn’t mean you have to go there. Since ES6, JavaScript has become a decent language imo while still carrying a lot of historical (and avoidable) baggage. Don’t forget how _old_ JavaScript is and that it’s still evolving to keep up with modern language developments :)

    • @robert.adamek
      @robert.adamek 6 ปีที่แล้ว

      What would you suggest then??

    • @taragnor
      @taragnor 6 ปีที่แล้ว +3

      Most languages seem to have weird nuances like this.

    • @rmrbush
      @rmrbush 6 ปีที่แล้ว +2

      Its the only language we can use in the browser. If C++ was the only language we could use on the desktop or servers then it would be the most popular. JavaScript has a monopoly. Someone could certainly develop a better language, but it would have to be adopted by all the major browsers. Awful.