5 Tips for Writing BETTER For Loops in JavaScript

แชร์
ฝัง
  • เผยแพร่เมื่อ 31 ต.ค. 2024

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

  • @barryglibb1448
    @barryglibb1448 2 ปีที่แล้ว +9

    If you do have to use a For loop, you get a marginal performance boost by setting the array.length as a variable in the first condition i.e. for(let i=0, len=array.length; i

  • @drakeno5015
    @drakeno5015 2 ปีที่แล้ว +11

    The main tip on loops - since 2020 there are handy constructs like "for...of" and "for...in", and no need to write rudimental i=0; i

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

      Speedwise there is a reason. Using a for loop has a lower runtime.

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

      @@mattxnyce Yep, the built in array methods are substantially slower on larger arrays, quite interesting it wasn't mentioned in this video; sure it is easier to read but the performance impact can be quite severe as a lot of time people seem to be chaining these methods instead of doing a single forloop which means you can potential go into n^k territory very quickly if you aren't careful >_>

  • @pjc825
    @pjc825 2 ปีที่แล้ว +49

    Please cover standard for loop vs For-Of loop vs For-In loop vs array.forEach() function as well as performance difference(speed wise) of each of these 😀👍

    • @JamesQQuick
      @JamesQQuick  2 ปีที่แล้ว +13

      That’s a great suggestion! Thanks for sharing that

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

      Yes! Just discovered the answer for this and it surprised the heck out of me.

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

      @@FelixSargent pls kindly share with me

  • @danser_theplayer01
    @danser_theplayer01 11 หลายเดือนก่อน

    To avoid rate limiting for example in a bot, inside a loop await a promise with a timer in it. Basically a generator function (which I really don't see a use for) but in a form of a regular function.

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

    i have built an web application to generate VSCode snippets and i use it everytime when i write a function which can be reused, this saved me a lot of time

  • @nowisdumb9773
    @nowisdumb9773 2 ปีที่แล้ว +7

    Making a video about Promises Awaits Async would be highly appreciated 🙏

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

    For #3, aside from "break;", there's a smaller short-circuit where you can stop that iteration and continue looping, using "continue;". This is good if you reached a desired point in a specific iteration and don't need to continue processing that iteration any more (but still need to process for others). Ie. you have a list of words, and need to find the index of the letter "s" in each word. Not the best example, but works.

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

    Love snippets, designed my snippets around react components / etc with typescript / prrops / etc, got a bit repetitive so this helps it :)

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

    The promises all way of doing it is really clever! Learned something new today, thanks!

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

    Loving your videosan, I've seen trillions on JS. Loving yours.

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

    Thanks James!

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

    If you don't need the entire for loop, it means it's a special case. Therefore I'd extract to a seperate function/method and use return instead of break

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

    Which theme you r using and which extention you are using for js suggestions

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

    Damn you are on it!!! I swear like an hour or so before this post I was searching for this info. Very timely video. Thanks

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

      Hahahaha yassssss! Love it

  • @thekwoka4707
    @thekwoka4707 2 ปีที่แล้ว +5

    4 is the one that matters.
    For loops are rarely needed compared to the actual array methods.

  • @robertdong5591
    @robertdong5591 2 ปีที่แล้ว +10

    Amazing tips as usual :)
    For the accumulator pattern, I find the nullish assignment to be quite neat.
    const word = 'pneumonoultramicroscopicsilicovolcanoconiosis'
    const lettersCount = {}
    for(const letter of word) {
    lettersCount[letter] ??= 0
    lettersCount[letter]++
    }
    console.log(lettersCount)

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

      Oh very nice! I don’t think I’ve used that before!

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

      The way you wrote it, it doesn't work. It will always store REAL LETTER COUNT + 1, as the line 'lettersCount[letter]++ will also run within the same loop iteration where it was initially assigned the value of 1.

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

      @@jorgeluismongeblanco6933 Thanks for catching that. Indeed the initialisation should be 0 and not 1. Amending the example.

    • @8koi245
      @8koi245 2 ปีที่แล้ว

      there's a good song whit that name

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

      a bit more short version
      const word = 'pneumonoultramicroscopicsilicovolcanoconiosis'
      const lettersCount = {}
      for(const letter of word) {
      lettersCount[letter] = (lettersCount[letter] ?? 0) +1
      }

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

    Thanks, James! your video is so insightful!

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

    Hi I like your theme. Can you share what them you are using and some customizations maybe?

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

    Morning everyone! Thanks for the vid James!

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

      Thanks for watching!!

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

    i find Promise.all recommendation very practical. Thanks.

  • @angel-pu7su
    @angel-pu7su 2 ปีที่แล้ว

    Great tips. Thank you.

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

    😲 so so efficient and sweet
    thank you so much!!!

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

    I write Angular code using TypeScript and use my own snippets to generate templates for various Jasmine testing methods. In addition to the included Describe and It snippets in VS Code, I have my own that output a much more full featured set for Describe for instance, with a beforeEach() block, a couple of it tests, etc.

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

      Do you have those snippets/examples of what you're describing in a github to share?

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

    awesome! very informative

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

      Glad you enjoyed it!

  • @anasal-sammarraie5788
    @anasal-sammarraie5788 2 ปีที่แล้ว +3

    Can you please share the extension that makes console.log directly next to the code

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

      what is extension, guys?

    • @anasal-sammarraie5788
      @anasal-sammarraie5788 2 ปีที่แล้ว

      @@tranlan4265 When you use VScode you can install extensions which help you out with your or sometimes it’s needed for some languages

  • @JoseLopez-oz5tn
    @JoseLopez-oz5tn 2 ปีที่แล้ว

    that last tip on when to use aysnc await or promises real was useful

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

    Would you mind sharing the font and theme you use in your editor? Really like them.

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

    Hey James, excellent tips! Just one note: I think that, on Tip #5 (minute 15:04), line 34, you are missing an 'await' before 'Promise.all(...)'.
    But then... how is it that it runs fine on your example? 🤔

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

      Ah great question. So, since the loadPokemon() function is defined as being async, it inherently will return a promise. This means that wherever this function is called, it will have to use await to wait for the results. So the returned promise is the promise that is created from calling Promise.all() without the await. That make sense?

    • @registerbnar7884
      @registerbnar7884 2 ปีที่แล้ว +4

      @@JamesQQuick
      The only problem I see with this line is, that you time it before the promise is resolved due to the missing await and thus the timing does not include the parsing of the results.
      One additional optimization you could do, would be to move the .json() calls into the previous Promise.all in chained .then() calls, as each .json() call can be performed once the corresponding fetch resolves and there is no need to wait until all fetches are resolved.

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

      @@registerbnar7884 Oh shoot you're right! Dang I botched that part. Great callout!!

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

    Can you please share the theme name and especially how plugin you use to preview print the array elements and thanks

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

    What’s the extension you’re using for inline console log displays?

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

      Quokka. It's the one he mentions in the beginning. It has free and paid plans, but the free version should do most of the heavy lifting.

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

    It looks like magic so I have a few questions at 6:42.
    1. How does the wordCount object automagically get the "key: value" pair formatting, or is that Quokka doing the magic in the console?
    2. How is the variable "letter" getting assigned/value all the time in the loop, it being a const? I mean even it it were a var/let, it looks on the surface that it is getting overridden by a new value every cycle of the loop, no?
    Thanks for your clarification.

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

      Still reasoning about it. Does each loop represent a distinct "stack" so that "const letter = word[i]" is an nth amount of declaration for the length/size of the cycle? Does it make sense what I'm asking? 😃

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

      @@k16e For 2., that's it, each iteration of the loop has it's own set of variables (it's own scope), that's why you can declare letter as const.
      For 1., it's typical when you are learning to see that kind of syntax and think it's magic, happened to me as well. But the fact is that it's just taking advantage of JS features.
      You can use strings to declare properties(keys) on an object, instead of using the dot.
      For example:
      let person = {};
      person["name"] = "John" // Person is now {name: "John"}
      As you can derive from this, inside the brackets you just pass a string, so that string can come from anywhere.
      let person = {};
      let prop = "name"
      person[prop] = "John" // Person is now {name: "John"}
      The next step is to see, you are iterating over an array of strings, and using their values directly to create and access keys of an object, it's plain Javascript, no magic involved :)

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

      @@inakiarias7465 Much gratitude for taking the time to clarify. Thanks

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

    Good stuff. I like these non-project tips and tricks!!!

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

    Thanks for the tips! I'm a big fan of using the array functions, but I have needed to use a for...loop (vice forEach) occasionally for that short-circuit pattern.

  • @justsample9185
    @justsample9185 2 ปีที่แล้ว +7

    Talking about for loops and not mentioning for-of and forEach?!

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

      Great point!! Maybe I’ll do a part 2

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

      No reason to use for each when for of is more efficient,more clear and concise

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

      @@arthasmenethil5748 actually, forEach is pretty useful because it chains with other array methods such as .map and .filter

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

      True. I just want to point out that in some cases for-of and forEach tend to perform slower than traditional for loop

  • @신-f8p
    @신-f8p 2 ปีที่แล้ว

    Which vscode extension do you use?

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

    I searched for such an extention fot a long time

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

    Isn't array.find() method the same as #3?
    Do we get any performance benefit writing for loop instead of more concise .find()

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

      probably but you shouldnt care about it until it is a problem

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

      To be honest, quite a noticeable performance hit. If you are worried about performance, use a for loop.

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

    For loops are more the exceptions. Array methods handle most of this.
    The first section should have used Array#forEach. The second section should have used Array#reduce. The third section should have used Array#find.

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

    Cool video! Thank you

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

    What's your editor font? l like it 😀

  • @Jonathan-o6b
    @Jonathan-o6b ปีที่แล้ว

    thx sir

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

    Hi James good to see you back! Hope you had a great time in Europe, can see that the jet lag kind of affects you 😉🤣. Really nice tips the accumulator pattern didn’t know about it so thanks.

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

      Glad you enjoyed it!!

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

    Are using fira font or is it sth else?

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

    6:24 If you're "accumulating" one good thing to do is to "reduce"

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

      Yes, reduce is a very handy tool!

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

    I just know if I run a loop, it repeat me a single thing again and again. I just want to know what are the usage of it. What can a loop do in my project?

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

    what theme is that?

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

    What theme is this?

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

    what is font you use in vscode?

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

      You can find info about my setup in my uses page. www.jamesqquick.com/uses/

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

    In the BMW loop, if you return "found it" instead of console log, the break is obsolete, isn't it? Since return stops the loop.

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

      It's not inside of a function in that case, but yes.

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

    I think you cannot use async/await in any “function” loop or map.
    If you want to use it the you should use for of loop or a regular loop ….

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

    I like your cursor animation. is that an extension? thanks for reply

    • @AbdulSamad-kn3ot
      @AbdulSamad-kn3ot 2 ปีที่แล้ว

      You can change that is settings

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

      Yep it’s just a setting in vs code!

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

    Really good explain it all promise

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

    Aw yes, my favourite tip about for loops. Don't write them. Couldn't agree more :D

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

    thanks for the video. it just tell about for loop how about while, foreach. ?

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

      Maybe I’ll do future videos on more loops!

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

    Too bad for loops are generally more efficient for runtime than array functions

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

    why no 'in' or 'of' in your array iteration?

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

    looks the same as doing for(let Car in Cars) no ?

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

    Anyone know the VS code theme he's using?

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

      shades of purple

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

    with todays JS ECMASCRIPT's api, you rarely need to use for loops.

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

    Does anyone know what’s the name of this theme?

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

    Ouches:
    - I don't like something like quokka constantly evaluating (compiling?) my code as I'm typing it. It's a distraction, a waste of CPU cycles for all the intermediate results that I ignore, and what if there are unintended and undesirable side-effects? (like calls to a database or an API, repeating things I don't want??)
    - Learn to type slowly and carefully .. okay, I know being in-front of an audience makes this harder, but maybe do another take?
    - Similarly, please pay attention to proper spacing, like '//1. ' -> '// 1.' and 'for(' -> 'for (' while coding, and don't neglect semicolons!

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

    Good tips. The tip count is actually more than 5 if you count seeing examples of how useful quokka and console.time can be. I agree that a Promise.all() post would be helpful. Really confusing to me what is going on inside the array of the fetches before it gets passed as a argument to Promise.all(), like why don't the fetches immediately fire off as they are instantiated rather than when sent to Promise.all()?

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

      Yeah that stuff is tricky to follow. I’m thinking about doing a specific follow up on Promise.all

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

    why not snippet for console.log itself...
    map is great but slower
    short compostable stuff lets you reason well but doesn't make the fastest thing, if you do codewars you learn it fast.

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

    The title says "BETTER For loops", but you just used some built in functions. There are not for loops but array functions. And the first example was about just how to generate a code snippet. I expected something about for-in for-or forEach and the basic for loop pro-cont things how they work in the background when to use which and why etc.

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

    Nobody uses words as long as we Germans. 😂
    Grundstücksverkehrsgenehmigungszuständigkeitsübertragungsverordnung
    Donaudampfschifffahrtselektrizitätenhauptbetriebswerkbauunterbeamtengesellschaft
    🤣🤣

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

      Hahaha das ist richtig :)

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

      @@JamesQQuick Hauptreichseisenbahnknotenpunkthinundhirschieber

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

    Promises are meant to be broken. 😂

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

    is Quokka free ?

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

    6) Cache your Array Length

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

      Not sure what you mean there?

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

      @@JamesQQuick he means it's best practice to declare and assign your array.length. There's a noticeable performance boost gained by doing so.

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

      @@mattxnyce Is that true though? The length property can be accessed in constant time, so in terms of BigO, you're adding negligible overhead? Maybe I'm wrong?

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

      @@JamesQQuick I wish I understood why so I could explain it to you. There's a weird way of writing it.
      let i = 0
      let len = array.len
      for(; i < len; i++){
      // stuff
      }

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

      @@mattxnyce Yeah I get what the code would be if you did that. I just don't quite understand why the performance implication if accessing .length takes constant time.

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

    B

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

    🤴🤴

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

    Brother please speak little bit slow, i am from non native English speaker places 🙏

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

    If you don't know dsa no matter how efficient you write your code you can never be as efficient as someone who knows dsa.

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

    Great JS Loop Tips. Thanks, James
    {2022-10-21}

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

    great video!. make a video on Promise.all()

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

      Adding it to the backlog!