DEV Community

loading...

Discussion on: Stop Using "data" as a Variable Name

Collapse
darkwiiplayer profile image
DarkWiiPlayer

when looping over multidimensional arrays

For two dimensions, i and j are still easy enough to follow. Starting at 3, it's very rare to not have better names resulting from context, like x, y and z for spacial coordinates, etc.

but many people do

They shouldn't. Iterating over data structures with C-style numeric for loops is a much worse habit than calling a variable data. But fair point on the intent of the exercise, sometimes we have to write "bad" code to avoid having to think up a convoluted example just to illustrate a very basic principle.

Thread Thread
cubiclesocial profile image
cubiclesocial

I've never understood why people use i and j for loop variable names. I prefer x, y, and z because they are generally used for looping spatially over an array (columns = x, rows = y, depth = z). Using x, y, and z also mirrors the Cartesian-like planes in mathematics fairly well. That is, anyone with a strong math background will understand x, y, z, and n intuitively while i and j are largely meaningless with i being used for imaginary numbers. i and j and l (lowercase L) are also the thinnest characters in many fonts, making them harder to read.

Thread Thread
drumstix42 profile image
Mark

Check out this Answer on StackOverflow:
stackoverflow.com/a/4137890/4035952

The answer is mostly because of Math, and what "i" and "j" stood for and it's pretty easy to understand how it made it's way into code. Luckily these days, simple "for" loops can be often be replaced with functional versions, or use "for...of"