Skip to main content

Command Palette

Search for a command to run...

The FOR loop dilemma in JS

Updated
2 min read
V

I am still deciding what should I write here.

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!

More from this blog

Vivek's Tryst with Tech

35 posts

builder of APIs, reducer of latencies, optimiser of code, fixer of issues

Backend Engineer | On my way to become 10x engineer