For Of & For In  ๐Ÿง

For Of & For In ๐Ÿง

ยท

2 min read

For Of ...

Mdn Defination

The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.

samajh-nahi-aaya-par-sun-ke-achha-laga.jpg

I know u didn't came here to read this ๐Ÿ˜‚ let me explain you in the easiest way possible.

for...of statement executes a loop over iterable objects(i.e objects which you can loop through) , such as arrays , strings , TypedArray , map , set , NodeList .

Still confused? ๐Ÿ˜ , yes I know, so now nail down the concept via some examples.

Example 1

const arr = [1, 2, 3];

for (const element of arr) {
  console.log(element);
}

Output

1.PNG

Example 2

const str =  "superman";
for (const i of str) {
    console.log(i);
}

Output

2.PNG

9c0d79f774cebd0431dfe0bde5a437af.jpg

Example 3


const iterable = new Map([
    ["a", 1],
    ["b", 2],
    ["c", 3],
  ]);

 for (const [key, value] of iterable) {
    console.log(key , value);
}

Output

3.PNG

wow-omg-meme.gif


For In ...

Mdn Defination

The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

4.jpg

Let me explain u ๐Ÿ˜

The for...in statement helps you to iterate over an object(i.e key , value) and helps you to extract them.

Example 1

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

Output

5.PNG

Summary

1) for...of helps to iterate over array, String, TypedArray, Map, Set, NodeList

2) for...in helps to iterate over object

Conclusion

6.jpg

ย