JavaScript for-loops are… complicated - HTTP203

Поделиться
HTML-код
  • Опубликовано: 10 сен 2024
  • 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

  • @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.

  •  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

  • @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

  • @StarCoreSE
    @StarCoreSE 6 лет назад +11

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

  • @GmoneyMozart
    @GmoneyMozart 6 лет назад +39

    This was fun. More videos like this!

  • @DebabrataAcharya93
    @DebabrataAcharya93 6 лет назад +17

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

  • @AlekseyNew
    @AlekseyNew 6 лет назад +11

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

  • @girlswithgames
    @girlswithgames 5 лет назад +25

    videos like these make me want to unlearn programming

  • @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

  • @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

  • @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

  • @ngneerin
    @ngneerin 3 года назад +1

    Love this series. Do more of these

  • @sreelalts1892
    @sreelalts1892 6 лет назад +3

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

  • @mikehallishere
    @mikehallishere 6 лет назад +58

    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 6 лет назад +1

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

  • @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..

  • @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

  • @karlheinzneugebauer
    @karlheinzneugebauer 6 лет назад +2

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

  • @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.

  • @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.

  • @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.

  • @pdcx
    @pdcx 2 года назад

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

  • @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. 6 месяцев назад

      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?

  • @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.

  • @adithyareddy6211
    @adithyareddy6211 6 лет назад +9

    This hurt my brain

  • @Challenge9000
    @Challenge9000 6 лет назад

    Learned so much, thank you.

  • @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 6 лет назад

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

  • @HashimWarren
    @HashimWarren 6 лет назад +4

    weirdly entertaining

  • @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?

  • @sy-hungdoan4859
    @sy-hungdoan4859 3 года назад

    Awesome !!! I literally unlearnt for loops

  • @pragyandas
    @pragyandas 6 лет назад

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

  • @HarryBallsOnYa345
    @HarryBallsOnYa345 2 года назад

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

  • @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.

  • @AbhishekKumar-mq1tt
    @AbhishekKumar-mq1tt 6 лет назад

    Thank u for this awesome video

  • @RomanLyubimov
    @RomanLyubimov 3 года назад

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

  • @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”.

  • @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

  • @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.

  • @Abhishek-dp5tc
    @Abhishek-dp5tc 3 года назад

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

  • @DenisTRUFFAUT
    @DenisTRUFFAUT 6 лет назад

    Wow. Mind blowing.

  • @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?

  • @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

  • @giacmoit
    @giacmoit 5 лет назад

    Awesome, it's really helpfull

  • @SurvTech
    @SurvTech 4 года назад

    This is soo cool.

  • @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.

  • @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.

  • @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"

  • @jayakrishnanjr5194
    @jayakrishnanjr5194 5 лет назад

    This is awesome

  • @shridharpatil8310
    @shridharpatil8310 6 лет назад

    This is great

  • @LeandroCoutinho
    @LeandroCoutinho 6 лет назад

    amazing crazy stuff

  • @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!

  • @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.

  • @salasiapro
    @salasiapro 6 лет назад +1

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

  • @sandeeptottadi
    @sandeeptottadi 3 года назад

    Had fun😄😄🤣

  • @yixunnnn
    @yixunnnn 6 лет назад +1

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

  • @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/

  • @neHCuoHEpa8888
    @neHCuoHEpa8888 6 лет назад

    HI, do anybody know is it same for swift?

  • @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

  • @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 :)

  • @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

  • @poloska9471
    @poloska9471 5 лет назад +12

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

  • @MartinOckovsky
    @MartinOckovsky 6 лет назад +1

    You guys are great!

  • @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% :)

  • @b3rakesh11
    @b3rakesh11 6 лет назад

    Awesome

  • @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?

  • @damians.7859
    @damians.7859 Год назад

    One year later I still get lost, maybe next year

  • @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.

  • @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

  • @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.

  • @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

  • @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.

  • @carloslfu
    @carloslfu 4 года назад

    hahaha, so funny! great job guys :)

  • @codingmaster6321
    @codingmaster6321 6 лет назад

    YEY ! google got a new sub !

  •  6 лет назад

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

  • @srsajjad7460
    @srsajjad7460 6 лет назад

    man ! this episode was dark

  • @bdjeosjfjdskskkdjdnfbdj
    @bdjeosjfjdskskkdjdnfbdj 5 лет назад

    need the draw the enviroment model haha

  • @uhl7792
    @uhl7792 6 лет назад

    The browser adds a buffer to setTimeout!! TIL!

  • @driziiD
    @driziiD 3 года назад +1

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

    • @sanjarcode
      @sanjarcode 2 года назад

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

  • @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.

  • @mrgerbeck
    @mrgerbeck 6 лет назад

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

  • @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 .

  • @sanjarcode
    @sanjarcode 2 года назад

    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

  • @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

  • @azwanabdullah7750
    @azwanabdullah7750 6 лет назад

    If I could understand all of these 😩

  • @dasten123
    @dasten123 5 лет назад

    Wow... just wow xD

  • @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

  • @lv85huenex
    @lv85huenex 5 лет назад

    so that was a funny intro

  • @kressckerl
    @kressckerl 6 лет назад +2

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

  • @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. 🙏🏻

  • @threestar4045
    @threestar4045 6 лет назад

    What a rich and wonderful language!

  • @BabekNagiyev
    @BabekNagiyev 4 года назад

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

  • @FauzulChowdhury
    @FauzulChowdhury 6 лет назад

    So now, we are missing the *pointer.

  • @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... :|

  • @chauvu8x
    @chauvu8x 6 лет назад +1

    Too much talking and too title illustration. It's hard for non-native English speaker like me to follow their chit chat.

  • @dwengs
    @dwengs 6 лет назад

    Of course I'm a little confused.

  • @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

  • @ayubbegimkulov8749
    @ayubbegimkulov8749 3 года назад

    But it's still faster than forEach)

  • @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.

  • @Noopkat
    @Noopkat 6 лет назад +2

    😂👏