: operator.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

: operator.

Post by JellyFish »

What does the ":" operator do, if it is an operator? Give some examples, along with a good explanation, on how ":" works.

Thanks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

It isn't an operator of it's own as far as I know. Off the top of my head, there are two uses for it in Javascript (I must assume you are referring to it since you posted in Client Side.) The first is with the ternary operator expression ? true-expression : false-expression. The other is involved in JSON where it follows a property/method name

Code: Select all

var foo = {hi: 'cheese', spam: 'tasty'};
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

Yes I meant JavaScript, thanks for that. :D But if it's not an operator then what is it?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

For the ternary, it's part of the operator, but it isn't the or a operator.

For JSON, it's a separator, like => is for array notation in PHP.
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

Wait a minute. What's the ternary operator? Is it "?"? I've seen this operator before and it was on my list of things to find out, so to speek. What does this operator to and how does it work?
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

So "?:" is known as the "Conditional Operator"? From my research, it seems kinda like an if statement.

Code: Select all

y=-1
x=(y<0)? 5: 10
So if the condition in parenthesis is true then the following after "?" is executed. If false then the following after ":" is executed. In the example above, x equals 5.

Correct me if I'm wrong. :)
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

that's right
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

Then I guess this topic is closed.

Thank you all for your efforts. :D
Post Reply