This digest is my own contribution to planet Knowledge today. You can join my Planet by clicking on the bottom of this article.

There was a code posted in the crowd today


      
  1. let foo = {};

  2. foo[foo['red'] = 1] = 'red';

Copy the code

And exclaimed:

Only to find that JS can also be written like this.

I do not know why he is so feeling, then asked a question, his answer is:

I didn’t know assignment had a return value.


Get back to me with this and I’ll have a rough idea. He may have read second-hand documents, or he may not have studied systematically.

Because in formal documentation, the word assignment “operation” is not used. Instead, expressions and statements are used.

Assignment “expressions” all return a value (any expression returns a value), but assignment “statements” do not.

B =5 is an assignment expression that returns 5, so we can write:

                            
      
  1. var a = (b = 5); // ok

Copy the code

But varb=5 is an assignment, so we can’t write:

                                
      
  1. var a = (var b = 5 ); // error

Copy the code

Throws an exception: UncaughtSyntaxError: Unexpectedtokenvar

Similarly, if is a statement, so we cannot write:

                                        
      
  1. var a = if(true ) { }

Copy the code

Is also very similar: UncaughtSyntaxError: Unexpectedtokenif


You might think: of course I know if can’t be assigned to a variable!!

But ~ ~ ~ ~

In some languages, especially functional programming languages, if-else is also a statement. The selling point of many functional programming languages is that they have expressions and no statements.

For example, in Kotlin, you could write:


      
  1. val max = if (a > b) a else b

Copy the code

Because its if(a>b)aelseb is an expression that returns a value, it can be assigned directly to Max.