Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ternary operator and assignment

I get unexpected result for this simple JavaScript assignment statement:

var t = 1 == 1 ? 1 : 0; undefined 

I would have expected to get 1 assigned to t instead. Same result if you do

var t = (1 == 1 ? 1 : 0); undefined 

Can somebody explain why this does not work as expected?

like image 506
faridz Avatar asked Feb 22 '11 15:02

faridz


People also ask

Can we use assignment operator in ternary operator?

both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.

Can ternary operator be used without assignment?

Nope you cannot do that.

What is an assignment operator in JavaScript?

Assignment operators. An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

How do you use and condition in a ternary operator?

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.


1 Answers

The result of evaluating var t = 1 == 1 ? 1 : 0; in, say, the Firebug console will be undefined. However, the value of t will be 1 as expected. Try outputting t after the assignment.

Firebug will print the result when the variable declaration is on a separate line:

var t; t = 1 == 1 ? 1 : 0; 

This is because the return value of an assignment operation is the value being assigned. However, when the var keyword is present, what's returning is the value of the VariableStatement declaration, which behaves as follows:

The production VariableStatement : var VariableDeclarationList; is evaluated as follows: Evaluate VariableDeclarationList. Return (normal, empty, empty).

Where Return (normal, empty, empty). refers to a type recognized by JavaScript internally, not something that would be printed to the console.

Further reading:

http://ecma262-5.com/ELS5_HTML.htm#Section_12.2

like image 129
Wayne Avatar answered Sep 25 '22 02:09

Wayne