简体   繁体   中英

Why assignments don't return undefined?

As you may know, JavaScript returns undefined for assignments, eg var a = 0; . However, TypeScript is not consistent with that fact, and seems to return the assigned value ( 0 ) – yet I could not find any information about this online.

As an example, see this code snippet.

 function f(): void { let l: number = 1; return (l = 2); // f() returns 2 } alert(f()); 

I would like to learn the reasons behind this decision, and to hear opinions about it.

Your code snippet contains return (l = 2) , an assignment , not return (var l = 2) (which is of course not valid code), the former will return 2 in JavaScript, TypeScript, or indeed C or Java.

A variable declaration var l = 2 is a statement, however only expressions have values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM