Search code examples
javascriptarraysmethodsoperator-precedence

What is the order of operations inside a return statement when having several methods?


In the following statement what would be the order of operations?

... return array.map(some funct).join().sort()

Is it from right to left or left to right? Or depends on the type of function present in the statement, meaning that every case is unique. If so what is a good rule of thumb to display the methods: which comes first and after that and so on?

Thank you


Solution

  • The property access operators have left-to-right associativity:

    array.map(func).sort().join()
    

    is the same as

    (((array).map(func)).sort()).join()
    

    It really wouldn't make sense the other way round, you couldn't even group it in a syntactically valid fashion.

    Regarding the order of evaluation, that is always left-to-right in javascript. In the case of method calls, there is only one sensible order anyway: evaluate the object, then access the property and evaluate it to the function value, the call that function.