• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript What does -1 do while using the Conditional (ternary) operator?

Malcolm

Administrator
Administrator
Staff Team
Hi everyone,

Could someone help me understand the code down below. I'm using a Conditional (ternary) operator that I got from this tutorial but having trouble understanding.

JavaScript:
index = index >= colors.length - 1 ? 0 : index + 1;

I believe I have a grasp of majority of it, but what I don't understand is what the -1 is doing?
 

Antero360

King Coder
Staff Team
Security Analyst
Hi everyone,

Could someone help me understand the code down below. I'm using a Conditional (ternary) operator that I got from this tutorial but having trouble understanding.

JavaScript:
index = index >= colors.length - 1 ? 0 : index + 1;

I believe I have a grasp of majority of it, but what I don't understand is what the -1 is doing?
Hey Malcolm,
so any time you see the ? and then : ... they are the short hand notation for an if-else statement. In this particular example, the -1 is part of the condition, checking whether index is greater than or equal to the length of the colors array minus one.
so that would evaluate to this
Code:
if(index >= (colors.length - 1)){
    index = 0;
}
else{
    index = index + 1;
}

so if say, the length of the array is 10, then you would have this
Code:
if(index >= (10 - 1)){
    index = 0;
}
else{
    index = index + 1;
}
 

Antero360

King Coder
Staff Team
Security Analyst
Thank you Antero!

For index, does that refer to the items within the array?
index refers to the position in the array you are either currently looking at if you are looping through the array, or, a position in the array that you are looking at, rather arbitrarily. So if you do, index+1, you are looking at the next position in the array, and if you do index-1, you are looking at the position before whatever index is
 
Top