loremIpsum1771
loremIpsum1771

Reputation: 2527

Proper way to return multiple variable from a javascript object

I'm currently learning more about the inner workings of javascript objects and came across an example where multiple variables were returned from the object:

var squareGrid = function(width, n, z) {
        width = width || 1;
        n = n || 4;
        var z = z || width / 2.0;

        var edges = [],
            pts = [];

        var step = width / n;
        for (var u = 0; u < n; u++) {
            var u_added = u * n * 4;
            for (var v = 0; v < n; v++) {
                var delta = u_added + 4 * v;

                var t_v = step * (v - n / 2);
                var t_u = step * (u - n / 2);

                pts.push([t_v, t_u, z]); // top left
                pts.push([t_v, t_u + step, z]); // top right
                pts.push([t_v + step, t_u + step, z]); // bottom right
                pts.push([t_v + step, t_u, z]); // bottom left

                edges.push([delta + 0, delta + 1]);
                edges.push([delta + 1, delta + 2]);
                edges.push([delta + 2, delta + 3]);
                edges.push([delta + 3, delta + 0]);
            }

        }
        return {
            edges: edges,
            pts: pts
        };
    }

In this case, in order to return both edges and points, it looks like there are key-value pairs being returned where the keys and values are the same thing. Is this method necessary or can the following just be done?

return{ edges, pts}};

Upvotes: 0

Views: 65

Answers (1)

Anchalee
Anchalee

Reputation: 666

You would be returning an object where the keys would be edges and the values would be the return value of edges.

x = squareGrid(400, 2, 5)

x.edges
// edges
x.pts
//pts

You could do something like: data = callfunction() -> return [edges, points]

data[0]
// edges
data[1]
//points

** Correction ** when keys are stored in a js hash it serializes the key before attempting to store the value

what would get stored is the serialized version of the array as the key, with the value being the array

Upvotes: 3

Related Questions