Why does this JavaScript work?

前端 未结 4 1365
难免孤独
难免孤独 2021-01-17 08:27

I was looking at the output of some stuff from UglifyJS and happened across some code like the following:

var a = 0;
var b = function () {
    return functio         


        
相关标签:
4条回答
  • 2021-01-17 08:47

    Check out the comma operator in JavaScript.

    The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

    0 讨论(0)
  • 2021-01-17 09:03

    The result of an expression using the comma operator is the right hand side of the comma operator.

    You have:

    return a_function_call(), a_string
    

    … so you get a_string assigned.

    0 讨论(0)
  • 2021-01-17 09:07

    First of all let me cite MDN on the comma operator:

    The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

    With that being said, it is clear, how your code evaluates:

    Inside the immediately executed function you return 2 values separated by a comma:

    function () { a++; }()
    

    and

    'Hello World'
    

    So both operands are evaluated. This increments your variable a and leads to the following expression for the return value of the function to create b:

    undefined, 'Hello World'
    

    Finally the right operand is returned as a value for the outer function, thus giving b the value 'Hello World'.

    0 讨论(0)
  • 2021-01-17 09:11

    It works due to the comma operator. From the MDN specs:

    The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

    Both functions are IFFYs, they are inmediately executed.

    0 讨论(0)
提交回复
热议问题