Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value returned by the assignment

Why does the regular assignment statement (say, x = 5) return the value assigned (5 in this case), while the assignment combined with a variable declaration (var x = 5) returns undefined?

I got the return values by executing these statements in the Chrome browser's Javascript console:

> var x = 5; undefined > y = 5; 5 
like image 254
user10165 Avatar asked Apr 16 '13 01:04

user10165


People also ask

What is the return value of an assignment?

Value of an assignment In most expression-oriented programming languages (for example, C), the assignment statement returns the assigned value, allowing such idioms as x = y = a , in which the assignment statement y = a returns the value of a , which is then assigned to x .

What is the value of an assignment?

The value of an assignment expression is the value of the right-side operand. As a side effect, the = operator assigns the value on the right to the variable or property on the left so that future references to the variable or property evaluate to the value.

Does assignment return a value in C++?

An assignment operator can return anything it wants, but the standard C and C++ assignment operators return a reference to the left-hand operand.

What does assignment return in JS?

Assignment operator doesn't return anything... In below example, first thing JS parser does is assigning 5 to y. Second thing is assigning y to x, and so on. Assigning is not return (it's not a function, and in JS it doesn't have C++ syntax to overload operator's behavior).


1 Answers

That's the way the language was designed. It is consistent with most languages.

Having a variable declaration return anything other than undefined is meaningless, because you can't ever use the var keyword in an expression context.

Having assignment be an expression not a statement is useful when you want to set many variable to the same value at once:

x = y = z = 2; 

It can also be used like this:

x = 2*(y = z); // Set y = z, and x = 2*z 

However that is not the most readable code and it would probably be better written as:

y = z; x = 2*z; 
like image 73
Paul Avatar answered Oct 11 '22 23:10

Paul