DEV Community

Cover image for Loops in JS
Manu Martinez
Manu Martinez

Posted on

Loops in JS

Loops wowww ๐Ÿ˜ƒ, incredible, it sound really strange, it's petty similar to the concept you already know.

What is exactly loops:

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");
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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]}`);
}
Enter fullscreen mode Exit fullscreen mode

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}`)
});
Enter fullscreen mode Exit fullscreen mode

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.

REPLIT

Top comments (0)