0

Possible Duplicate:
JS How to use the ?: (ternary) operator

I download one plugin for wordpress in that plugin there is one javascript. Into that js code I don't understand how it works.

function ddet_javascript() {

echo '
<script language="JavaScript" type="text/javascript"><!-- 
function expand(param) { 
param.style.display=(param.style.display=="none") ? "" : "none"; 
 } 
  //--></script>';
}

In this code I don't understand the line given below.

param.style.display=(param.style.display=="none") ? "" : "none";

what is the use of ? and : in this line. please let me know if anyone know about it.

Community
  • 1
  • 1
wasim kazi
  • 368
  • 4
  • 12

7 Answers7

3

It is an operator:

(condition) ? true : false

It is like:

if(param.style.display=="none")
       param.style.display="";
else
       param.style.display="none;
ragklaat
  • 858
  • 5
  • 12
2

This is ternary operator. it's works like if else statement.

view this link:

http://davidwalsh.name/learning-ternary-operators-tips-tricks

http://jqfundamentals.com/#example-2.16

Hkachhia
  • 4,130
  • 5
  • 35
  • 71
2

It's the ternary conditional operator: The expression

Cond ? a : b

evaluates Cond and lazily returns a if it was true, and otherwise returns b.

The entire result of the expression in your case is assigned to param.style.display. In other words, if display is already set to "none", it will be set to "", and otherwise it will be set to "none".

This operator is common in many languages, since it provides you with a single expression whose value is conditional on something.

Kerrek SB
  • 428,875
  • 83
  • 813
  • 1,025
  • I really want JavaScript to include a second ternary operator so everyone gets confused. (Just kidding, I only sort of want it) – ChaosPandion Aug 30 '12 at 05:33
2

In your code it works like this:

if(param.style.display=="none"){
   param.style.display = "";  
} else{
    param.style.display = "none";  
}
Codegiant
  • 1,960
  • 1
  • 18
  • 27
1

It is called conditional (ternary) operator.

test ? expression1 : expression2

If test is true, it returns the expression 1 else returns expression 2.

And this is not specific to jquery but a javascript operator.

For more info, ternary operator javascript

Senthil Kumar
  • 8,157
  • 7
  • 33
  • 44
  • 1
    +1 for getting the name right (ecma-international.org/ecma-262/5.1/#sec-8.4). :-) – RobG Aug 30 '12 at 06:05
0

x=a?b:c, ?: is a ternary operator (works on 3 operands). It means if a is true then x=b else x=c

Prashant
  • 142
  • 1
  • 16
0
if (param.style.display=="none")
  param.style.display = "";
else
  param.style.display = "none";
Victor
  • 633
  • 5
  • 9