I was reading about the ternary operator in different languages, and noticed something interesting in the Javascript section. http://en.wikipedia.org/wiki/%3F:#JavaScript
The conditional operator in JavaScript has the same syntax and precedence structure as in the other BCPL-derived variants, but a significant difference exists in the semantics: it returns an l-value.
The first sentence states that the return of the ternary in javascript is an lvalue, so I tried some examples, with odd results (in the chrome console).
Given:
var a = { 'yo' : 'momma' }
var b = { 'yo' : 'cool' }
var bool = true
(bool? a : b).yo = 'LLJ'
//a is now { 'yo' : 'LLJ' }
(bool? a.yo : b.yo) = 'LLJ' //throws a reference error
Why does the first work and the second fail? (Logically they're the same statements, no?)
Ternary conditional operator will yield an lvalue, if the type of its second and third operands is an lvalue.
In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c .
This is important because the "binary +" operator does different things depending on the type of its operands: if a was a string, a + b would mean "append two strings together" rather than "sum two numbers".
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Wikipedia was wrong. The conditional operator returns an r-value, not an l-value.
The history of the article is quite interesting, so I've summarised it here:
30 August 2010: The Beginning
JavaScript section created. Correctly says that in JavaScript the ternary operator returns an r-value, but incorrectly says that in C/C++/Java it returns an l-value. Only in C++ the ternary operator returns an l-value.
31 January 2011: Cannot yield an l-value in C
C correctly removed from the JavaScript section because it doesn't return an l-value. Java remains.
15 February 2011: "Corrected"
The comparison to Java and C++ is removed (the comment correctly says that Java never yielded an l-value), but oh no! JavaScript suddenly returns an l-value!
7 March 2011: Hope is restored...
The incorrect "l-value" is changed to "value", linking to the Value article (which describes both l-values and r-values).
7 March 2011: ...but not for long
The link text is changed to say "l-value".
7 September 2013: Three cheers for Qantas 94 Heavy!
Thanks to this question, Wikipedia has been corrected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With