How To Use
- Anything before the (? sign) is the condition to check.
- Anything before the (: mark) will be the value of the variable if the condition is TRUE.
- Anything after the (: mark) will be the value of the variable if the condition is FALSE.
Is there any similarity between this operator in JS and in PHP?
Yes! They are alike both in syntax and in structure and they both do the same thing.
Check out its implementation
Supposing I have a variable that sets the username of a user based on the name on his profile
In the image above, the user has no name attached to his profile, so his userName will be Anonymous
You can visualize what the ternary operator did using the syntax below
So if we assign a value to the name variable, what will be the userName?
Yes, you got that right! The new name will be the userName