Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • 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.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • 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
Code Plus
Company Plus
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?
 
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;
}
 
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
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom