Is the assignment operator really “just” an operator?

前端 未结 3 1467
遇见更好的自我
遇见更好的自我 2021-02-14 23:22

My question was triggered by this discussion on SO, which did not lead to an answer that would really explain the issue. I am "rewriting" it here in a slightly differe

3条回答
  •  忘掉有多难
    2021-02-15 00:03

    I think the understanding of 1 && (a = 3) is, understandably, mislead.

    a = false
    b = 1
    b && a = 3
    b
    => 1
    a
    => 3
    

    Why is a being assigned to in the && expression when a is false? Should the && expression not return when encountering a false value? Spoiler, it does return!

    Taking a step back, we think of the purpose of the && operator to control the flow of logic. Our disposition to the statement

    1 && a = 3
    

    is to assume the entire statement is returned if a is nil or false. Well no, the interpreter is evaluating like so:

    (1 && a) = 3
    

    The interpreter does not raise a if it is nil or false nor does it return the left side if a is nil or false

    a = nil
    1 && a
    => nil # a was returned
    

    The interpreter returns the variable, this is why the original statement can be read:

    a = 3
    

    due to 1 && a returning a which is a variable that can be assigned to by the = operand on the second half of the statement.

    TLDR

    In your origin example: 1 is neither nil nor false so the variable a is returned in (1 && a) which is subsequently assigned in a = 3

提交回复
热议问题