Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Iterating String.split() working differently than I expected

I am writing a simple javascript code to parse, and verify a chess position written in Forsyth–Edwards Notation (FEN).

The default chess position in this notation is given by,

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

There are 6 components, I split the components by whitespace using String.split(" "), I now want to further split the first element of the resulting array by "/", which will give the state of each rank.

Running this code gives me an unintuitive result...

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
const locations = defaultFEN.split(" ")[0];

for (let rank in locations.split("/")) {
   console.log(rank);
}

I expected the output to be 8 Strings, delimited by "/", in the first portion of the defaultFEN string. Instead I get the numbers 0-7 printing out.

Interestingly, If I manually access this array, console.log(locations.split("/")[i]), for any number i in the interval [0-7], I see the result I intended.

Why are the numbers 0-7 printing out when using the iterative loop, but it works exactly as intended if I use a normal index based for loop?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There's nothing wrong with your split, but you should use for..of (MDN) instead:

for (let rank of locations.split("/")) {
   console.log(rank);
}

... as for..in loop iterates over indexes (and those are 0..7 for 8-element array).

As a sidenote, it's (usually) a good idea to use const (and not let) in this iteration, as variable is assigned a value once each loop (and usually shouldn't be reassigned):

for (const rank of locations.split("/")) {
   console.log(rank);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!