3

I am trying to decipher the following line of JavaScript code:

delay_start = (typeof delay_start_qs !== "undefined") ? !(delay_start_qs === "false") : true;

Specifically the ? followed by the !. Is that a comparison operator?

federico-t
  • 11,157
  • 16
  • 58
  • 108
  • 1
    no it is a ternary operator, a short way of writing an if statement – Zevi Sternlicht Sep 12 '13 at 23:00
  • The `?` is part of the ternary operator, the `!` is a negation operator applied to the result of the first branch, and `:` is the second part of the ternary operator. – Thilo Sep 12 '13 at 23:03
  • If this should be closed, why not this -. http://stackoverflow.com/questions/18774863/what-does-php-syntax-var1-var2-mean ?? [a real RTFM getting incredible upvoting in the answers, and certainly asked 100 times before] It seems rather random and very unclear how and when which questions people are voting for closing. – davidkonrad Sep 12 '13 at 23:21

4 Answers4

2

Its a simple ternary operator in play.

delay_start = (typeof delay_start_qs !== "undefined") 
                                ? !(delay_start_qs === "false") : true;

Lets break it..

(typeof delay_start_qs !== "undefined") // If delay_start_qs is undefined

if above condition is true then delay_start = !(delay_start_qs === "false") ;

otherwise delay_start = true;

The same can be written as a for loop

if(typeof delay_start_qs !== "undefined") {
    delay_start = !(delay_start_qs === "false") ;
} else {
    delay_start = true;
}
Sushanth --
  • 53,795
  • 7
  • 57
  • 95
2

It's the ternary operator.

value = condition ? <if condition is true statement> : <else statement>
federico-t
  • 11,157
  • 16
  • 58
  • 108
2
x ? y : z

Read the above as:

if(x) {
  y;
} else {
  z;
}

or:

if x then y else z

The ! means not. It has no relation to the ?. So what you're looking at is more like this:

if x then (not y) else z
grandinero
  • 968
  • 9
  • 15
0
delay_start = (typeof delay_start_qs !== "undefined") ? !(delay_start_qs === "false") : true;

is the same as

delay_start = (typeof delay_start_qs !== "undefined") ? delay_start_qs !== "false" : true;

because !(x === y) is equivalent to x !== y when neither x nor y are NaN. And the whole is the same as

delay_start = (typeof delay_start_qs === "undefined") ? true : delay_start_qs !== "false";

because x ? y : z is the same as !x ? z : y. And the whole is the same as

delay_start = (typeof delay_start_qs === "undefined") || delay_start_qs !== "false";

because x ? true : y is the same as x || y when typeof x === "boolean". And the whole is the same as

if (typeof delay_start_qs === "undefined" || delay_start_qs !== "false") {
  delay_start = true;
} else {
  delay_start = false;
}

because a = x ? y : z; is a statement that uses x to decide which of y or z to assign to a.

Mike Samuel
  • 109,453
  • 27
  • 204
  • 234