Help me understand this code

Please break down this code for me so I understand the logic behind it

function itemlsPresent (array, item) {
for (×=0; × < array.length; x++) {
if (array === item)
return true:
} return false;

I understand the first line, but then I get lost in the function body. I’m particularly having a hard time understand this portion of the code:
for (×=0; × < array.length; x++) {
if (array === item)

Hi Kyndra,

I’m a little new to this myself. Looks like this is a For loop. It has a few elements to it.

x = 0;
This expression creates a variable named x which is initially set to 0.

Each time the body of the loop executes, the value of x increases by 1.

x < array.length
The for loop will continue to run until the value of x becomes equal to the length of the array. So for example, consider the simple array [1, 2, 3, 4, 5]. The length of that array is 5. So the loop mentioned about would run 5 times in total. The first time, x would be equal to 0. Then it is increased by 1 so the second time the loop runs it is equal to 1. The third time, 2. Fourth, 3. Fifth, 4. Then before running the body of the loop for a sixth time, it will check that x is less than 5. It is no longer less then 5 so the loop terminates which is just as well because we’ve reached the end of the array.

if (array === item)
Finally, the actual body of the loop. It checks to see if each instance of “array” is equal to the value of “item”. If it is equal, it returns the value “true” meaning, this item exists in this array of values. If the for loop completes without finding the value in the array, it returns false, meaning this item does not exist in this array of values.

I hope that helps.


This line just loops through the number between 0, and the length of the array array.

  • The x=0 just creates a variable x, and assigns its value to 0.
  • The second part (x<array.length) checks at every iteration of the loop (every time the loop runs). If the condition x being less than the length of the array, is not met, then the loop stops.
  • The last part (x++) adds one to x after every iteration of the loop.

All this does is check to see if the element of array at position x (remembering that list indices start at 0, not 1). is equal to item.

I hope this helps!

EDIT: Sorry @spencerconrad; I hit post at the same time as I saw your post get posted…