26
Loops in JS
Loops
wowww π, incredible, it sound really strange, it's petty similar to the concept you already know.
Loops is a resource π₯° that allows you iterate data or to do an action the needed times. For instance, you can print Hello
in console twice without writing the console.log
statement twice.
console.log("Hola");
console.log("Hola");
It's the worst approach you can do, here, I'm really glad to introduce you looping
:
for(let i =0; i<2; i++) {
console.log("Hola");
}
It's look likes a joke π₯Ά, but no, imagine you need to write 1K times "Hello" in console, would you write console.log("Hello")
1000 times?
If your answer is YES
, let me say you're crazy π¨π»βπ»
Yes, this is the main aim of this type of loops
but there are more methods to achieve this aim
π when you are trying to parse an array
, let's see an example:
const data = ["a", "b", "c"]
for (let item of data) {
console.log(item);
}
This code will print three lines, one per item on the array, here you can see how this code looks like, also you can use loops
to get each key of a key-value pair (objects), let's see an example:
const data = {
"a": 1,
"b": 2,
"c": 3
}
for (let key in data) {
console.log(`key: ${key} @ value: ${data[key]}`);
}
Here, you can see π that we're printing all the pairs key-value
from the above object, it allows us to load an object without knowing anything about the length or the properties it could have.
Yes, I know, it bring us a lot of extra possibilities to work π with the data you need, objects
, arrays
.
Also, there is another methods to perform an array looping
, for example a forEach
sentence, which return a callback
with the execution for each value, let's see an example:
[1,2,4].forEach((value, index) => {
console.log(`The value in index ${index} is ${value}`)
});
This code allows you to run specific sentences per each item on the array π.
I know that there are more methods like map
but its aim isn't exactly to iterate each item on a array, we'll see it on the following posts.
That's all for the today post, I hope you have just learnt a lot, I mean you have understood what looping
means and how it looks using JS.
I strongly recommend you to take a look about it using real code, you can use replit to see what are you writing in real time.
26