Monday, May 20, 2024
11
rated 0 times [  17] [ 6]  / answers: 1 / hits: 27213  / 11 Years ago, tue, april 16, 2013, 12:00:00

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

More From » assignment-operator

 Answers
21

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;

[#78885] Sunday, April 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;