Jeff Storey
Jeff Storey

Reputation: 57202

javascript variable declarations after return statement

I was looking at some minified javascript code (from github), and the code has a block that looks like

h = function(a, b, c, d) {
        var e, h, i, j, k, l, m = this;
        return i = $("#js-frame-loading-template").clone().show(), l = c === "back" ? 350 : 500, j = i.find(".js-frame-loading-spinner").hide() // more stuff here

I'm curious why/how this code works since there are variable declarations after the return statement

Upvotes: 2

Views: 168

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

Let me introduce you to the comma operator.

Everything to the right of the return statement is one expression, consisting of multiple "sub-expressions", separated by commas:

return a, b, c, d;

Each sub-expression is evaluated, from left to right, and the value of the last one is the result of the whole expression. I.e. the result of the last expression is returned in this case (the results of evaluating d and whatever hides in // more stuff here in your example).

It's a "trick" to squeeze multiple expressions into one.


Nitpick:

[...] since there are variable declarations after the return statement

There are no variable declarations in that line, only assignment expressions. You could not have a var statement (a variable declaration) there because the comma operator (and the return statement), only works with expressions, not statements.

Upvotes: 6

Related Questions