Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...