'x' or 'i', does it matter?

Tell us what’s happening:

Why is ‘x’ being used and not ‘i’ in this excercice?
Does it matter if we use ‘x’ or ‘i’? Wouldn’t both be just the same?

Your code so far


// Setup
var contacts = [
{
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
},
{
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
},
{
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["JavaScript", "Gaming", "Foxes"]
}
];

/*
function lookUpProfile(name, prop) {
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name) {
    if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
    } else {
        return "No such property";
    }
}
}
return "No such contact";
*/

function lookUpProfile(name, prop){
for (var x = 0; x < contacts.length; x++){
    if (contacts[x].firstName === name){
        if (contacts[x].hasOwnProperty(prop)){
            return contacts[x][prop];
        } else {
            return "No such property";
        }
    }
}
return "No such contact";
}

lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:75.0) Gecko/20100101 Firefox/75.0.

Challenge: Profile Lookup

Link to the challenge:

Welcome, ranson.

It does not matter. i is just commonly used because you often index into objects in a for loop.

Any variable name can be used.

Hope this helps

3 Likes

The reason is simple
Just like in mathmatics you might remeber this from school.
They often use x as a placeholder. In since coding is close related to it we use the same.
Does it really matter wherenever it is an x , or z. Captial no.

2 Likes

This certainly helps!
Thank you very much for replying!

it’s good practice to avoid using x or i or any other placeholder and instead use a name that actually represents what it is.

So if you are looping over a list of books, then use book instead of i. If you are looping over a list of animals then use animal instead of i

2 Likes

I get why you’re suggesting this!
I never really thought this trough while making the excercices!

Thank you, it’s a very good tip!
I appreciate it!

While I agree, it is better to use variable names that describe the data they represent, then the following makes more sense:

var movies = ['Star Wars', 'Jaws', 'Dumb and Dumber'];
for (var index = 0; index < movies.length; index++) {
  console.log(movies[index]);
}

than:

var movies = ['Star Wars', 'Jaws', 'Dumb and Dumber'];
for (var movie = 0; movie < movies.length; movie++) {
  console.log(movies[movie]);
}

Now, if I were using a for of loop, then using a movie variable would make more sense.

var movies = ['Star Wars', 'Jaws', 'Dumb and Dumber'];
for (var movie of movies) {
  console.log(movie);
}

The point is, it really depends on the code being written.

4 Likes

yeh I was thinking in the context of mapping over an array rather than using a for loop as per OP question. In the case of a for loop then index does make more sense than x or i

1 Like

index is just needless verbosity: i is perfectly fine for looping over indices, and anyone who’s spent more than a month programming will recognize it. It should have a limited scope, since loops and other control structures shouldn’t be very large anyway.

Thing is, you hardly ever need indexes when iterating, and even if you do, the map and foreach methods pass the index to the callback as an extra parameter, among others (I consider that a feature-itis wart, and no other language does this, but if you need it it’s there). Once you start using those methods, give things descriptive names.

Funny thing is once you start defining your own higher-order functions, they become generic enough that there isn’t any really descriptive name for the variables anymore. I tend to go with item and func then, but many other programmers just go with x and f

One thing’s for sure: x for a loop index is definitely against convention, unless of course you’re iterating over a geometric grid and expect it to go with a y

2 Likes

I’m sorry for this late response!
Thank you very much for your replying!
I appreciate it!
I’m not sure yet what I’ll use. “Item and func” or “x and f” :’-)

Thanks again!

I’m sorry for this late response!
Thank you for replying!
I agree, it depends on the code being written. But I’ll definitely apply these tips! Thank you!

index is just needless verbosity:

The fact that this thread exists, immediately disproves this.

anyone who’s spent more than a month programming will recognize it.

oh right…you’re this type of developer…

The use of i as an iterator for index values is extremely common. It’s nearly ubiquitous in tutorials, texts, classes, and the like. I think its totally reasonable to assume that anyone who’s spent more than a month programming will recognize it.

Let me clarify something I said in an earlier post. While I think idx, index are fine and make it extremely clear (IMHO), most programmers will instantly recognize the variable i as being the index of an array when used in a loop of any kind. My main point was a variable name like x is not widely used and would be better to name the variable to reflect what it represents.

I agree that i is very common and most developers will recognise that it references the index.

My point is that when it comes to naming variables generally, it’s a better practice to veer on the side of verbosity for readability sake. Whilst i is the easiest example, there are a lot of abbreviations that may be common for some developers but not others e.g. e, acc, curr.

IMO readability is the sensible thing to optimise for especially when there are junior developers and considering the code gets minified anyway.

There are also ESlint rules to prevent this type of unneccessary abbreviation, which shows this view is shared - https://github.com/sindresorhus/eslint-plugin-unicorn/blob/master/docs/rules/prevent-abbreviations.md

I’m all for using words as variable names. I only use abbreviations in a handful of circumstances. But i is so ubiquitous that even ESlint’s verbosity recommendations don’t mention it.

Expanding i to index as a loop iteration is not intrensically more readable. Using i is standard practice and defying standard practices without good reason hurts readability.

With an 80 character line limit, I will ask developers to refractor out unnecessarily verbose iterators.

for entry in array:
   foo(entry) 

is preferred; however

for i in range(len(array)):
    foo(array[i]) 

is fine and is probably more natural in a multi-indexed object. I would have to see the exact use case. But

for index in range(len(array)):
    foo(array[index])

is visually noisy, eats space unnecessarily, and defies standard practices for iterator naming conventions.

You do you, but using i is common and there are good reasons for this.

My last word on the subject is a more big-picture thing, because I just roll that way:

Avoid iterating over indexes at all when you can. Just like const should be your default for declaring variables, for..of and methods on the Array class should be your primary tools for working with arrays. When there’s exceptions to this advice, you’ll know them, since they’ll stand out as the less common special cases they are.

1 Like