Skip to main content

The FOR loop dilemma in JS

Published 2 min readMarkdown

When I first started with Javascript, there was a lot of friction. I'd make syntactical mistakes that would result in hours of debugging. One of the reason I like languages that compile first. Today, I'll take you through a dumb syntactical error that had my head spinning.

The for loop

function workThatForLoop() {
  const data = [1, 1, 2, 3, 5, 8, 13];
  for (let start in data) {
    console.log(start);
  }
}

workThatForLoop();
Output:
"0"
"1"
"2"
"3"
"4"
"5"
"6"

Now, one would think for loop with 'in' keyword will loop through the values inside the array but noooooope.

And it outputs a string not an int.

Let's move to the next for loop syntax

function workThatForLoop() {
  const data = [1, 1, 2, 3, 5, 8, 13];
  for (let start of data) {
    console.log(start);
  }
}

workThatForLoop();
Output:
1
1
2
3
5
8
13

The above for loop loops through the values inside the array and prints them as they are, meaning if they are string then it will output the string.

I was a little taken back with the syntax, after working with JS for some time, I still make the above mistake. :'((

I am just saying that the syntax could be more developer friendly.

Anyway, you understood the difference, right? So be mindful. Learn from my mistake.

Cheers!

About the author

No comments yet. Be the first to comment.