JavaScript - for...of 및 for...in

안녕! 봉쥬르! 헤이!こんいちは !👋 오늘은 JavaScript에서 for...offor...in에 대해 배웠을 때 이야기를 해보려고 합니다.

내용의 테이블


  • Introduction
  • For...in
  • For...of
  • Summary

  • 소개

    If you are learning JavaScript (JS), at some point you will learn about loops in order to run a block of code over and over again. Loops are handy but sometimes they can be the source of your bug/trouble when you don't handle the loop conditions properly, this is especially true with while loops (I have created infinite loops many times, even more than Christopher Nolan 😋). The first loop statement I learnt in JS was a for loop, it was cool to be able to get the computer to repeat a task with set conditions but I did think that it required a fair bit of set up with the three statements when setting up the loop (and many times I forget about the semi-colon...😵).

    Later, I started using and it was fun to use them and they were very helpful in keeping the code clean while also expanding my knowledge. However, when solving some Data Structure and Algorithm problems, I found that if you need to break out of the loop early, Array methods are not good for those situation as they run on every element in the array, so I learnt about for...in and for...of to use something other than a for loop.

    ...에 대한

    The for...in loop iterates over the "keys" or "properties" of a JS Object and indexes of a JS Array , to put it simply. However more generally, it loop over the enumerable properties of objects, these are properties which are of String datatype and has an internal enumerable attribute sets to true (almost everything in JS is an object).

    The set up looks something like this.

    for (const key of object) {
      // something you'd like to do
    }
    

    If you want to loop through an object in JS, the for...in loop can be a very easy way to do that as it will iterate over all the properties of the object (including inherited ones) and then you can access the corresponding values. In the above code example, the variable "key" will represent different object properties each iteration.

    For example:

    const FFMovies = {
      first: "The Fast and the Furious",
      second: "2 Fast 2 Furious",
      third: "The Fast and the Furious: Tokyo Drift",
    }
    
    for (const installment in FFMovies) {
      console.log(installment + " is " + FFMovies[installment])
    }
    // first is The Fast and the Furious
    // second is 2 Fast 2 Furious
    // third is The Fast and the Furious: Tokyo Drift
    
    

    It is recommended not to use for...in loop to iterate over an Array if the order of matters, instead stick with for loop or use .forEach() method. This is to do with the implementation of the browser.

    ...의

    The for...of loop was introduce with ES6 which allow you to iterate over an iterable object in JS e.g. Array , String , Map and etc. To simply put, you can iterate over the values of an array for example. It is important to note that you cannot use for...of on Object directly.

    The set up of a for...of is very similar to a for...in loop except one word. So why would you use for...of instead of a regular for loop or a method like .forEach() ? I will show you.

    Example:

    const FFMovies = [
      {name: "Fast & Furious", installment: "4th", rating: 6.5},
      {name: "Fast Five", installment: "5th", rating: 7.3},
      {name: "Fast & Furious 6", installment: "6th", rating: 7}
    ];
    
    for (let {name, installment, rating: rated} of FFMovies ) {
      console.log(`${name} is the ${installment} of the franchise, it was rated ${rated} of out 10.`);
    }
    
    /*
    Fast & Furious is the 4th of the franchise, it was rated 6.5 of out 10.
    Fast Five is the 5th of the franchise, it was rated 7.3 of out 10.
    Fast & Furious 6 is the 6th of the franchise, it was rated 7 of out 10. 
    */
    
    

    With for...of you can directly use object destructing or array destructing which allow you to "grab" each properties/element and assign them to a variable to use inside your loop, just like the example above.

    When dealing with matrix problem, I often use this method to grab the directions so I can perform Breadth First Search for example.

    요약

    If you want to iterate through an array where the order of iteration matters, the traditional for loop is still a good method to use, alternatively you could use a .forEach array method. If you want to iterate over an object properties, you could use for...in to iterate over the object keys/properties and do what you want. If you have a more complex Array structure, you could use for...of loop combined with Array Destructing or Object Destructing to write cleaner code.

    That's it. I was aware of these two statements but I had never used them until I started solving DSA problems, and now I have this under my tool belt to use in the future 😄.

    As always, please leave a comment, like, feedback or whatever you want. Thank you for reading.

    좋은 웹페이지 즐겨찾기